user1263981 user1263981 - 2 months ago 15
C# Question

My first Unit Test

I am new to Unit Testing and just created a one small test for my word ladder function.

Can anyone pls advise if it looks okay and if it is a right way of doing it?

Also, is there a way to add a test to current project indtead of creating a sepereate Unit Test project in VS2012?

[TestMethod()]
public void MyFirstUnitTest()
{
string f = "hit";
string s = "cat";
string test= "";
List<string> lst = new List<string>();
test = wordLadder (wordList, f, s);
test = lst.ToArray;
Assert.IsTrue(test == "hit,hat,cat");
}

Answer

UnitTests are basically said to be composed of three parts: Arrange, Act and Assert

We can clearly see all three parts there, being

Arrange

string f = "hit";
string s = "cat";
string test= "";
List<string> lst = new List<string>();

Act

test = wordLadder (wordList, f, s);

Assert

Assert.IsTrue(test == "hit,hat,cat");

However, the points I would highlight are:

  1. Do not name variables f, s or any other names which are not intuitive to people who will be reading the test in future.

  2. Do not name your test method as MyFirstUnitTest. The method name should at least expose what the method is in fact testing

  3. What is wordList? Where is it defined?

  4. Finally, Assert.IsTrue(test == "hit,hat,cat"); is not the right approach. You basically will want to use that when testing some boolean returned value. To test a given value against an expected value, use Assert.AreEqual(expected, actual)

Take a look at this excelent piece of article for some information that might be useful (Link)