RSSAll Entries Tagged With: "unit test"

Technique of test-driven development

Test-driven development begins by writing a test that fails; then you move on to creating the production code, seeing the test pass, and continuing on to either refactor your code or to create another failing test.
Steps:

Write a failing test to prove code or functionality is missing from the end product.

Make the test pass by writing [...]

Generic implementation of simple unit test in csharp

Unit-testing frameworks can help make helper methods more generic like this, so tests are written more easily.
Test implementation:

 
public class TestUtility
{
public static void ShowError(string test,string message )
{
string msg = string.Format(@"{0}-{1}", test, message);
Console.WriteLine(msg);
}
}
public static void TestReturnsZeroWhenEmptyString()
{
//use .NET’s reflection API to get the current method’s name
 
string testName = MethodBase.GetCurrentMethod().Name;
try
{
SimpleNumber p = new SimpleNumber(); //testing the simpleNumber method from [...]

Simple unit test in csharp

Class to be tested:

public class SimpleNumber
{
public int ParseAndSum(string numbers)
{
if(numbers.Length==0)
{
return 0;
}
if(!numbers.Contains(","))
{
return int.Parse(numbers);
}
else
{
throw new InvalidOperationException(
"I can only handle 0 or 1 numbers for now!");
}
}
}

Unit test for class:

class SimpleNumberTests
{
public static void TestReturnsZeroWhenEmptyString()
{
try
{
SimpleNumber p = new SimpleNumber();
int result = p.ParseAndSum(string.Empty);
if(result!=0)
{
Console.WriteLine(
@"SimpleNumberTests.TestReturnsZeroWhenEmptyString:
Parse and sum should have returned 0 on an empty string");
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}

Running coded tests via a simple console application:

public [...]

Characteristics of a good unit test

A unit test should have the following properties:

The unit test should be automated and repeatable.
The unit test should be easy to implement.

The unit test must be usable in future situations.

The unit test should be easy for any developer be able to run it.

The unit test must execute quickly.