Unit testing in Java and C#

Unit testing has become a cornerstone of modern software development. Some of the most popular frameworks for unit testing are collectively known as xUnit. Originally developed for Smalltalk, there are now xUnit frameworks available for many programming languages. The current version 4 of the popular JUnit framework for the Java programming language uses annotations to mark test methods. A very simple test might look as follows.

public class SimpleTest {
    @Test
    public void testSimpleClass() {
        SimpleClass s = new SimpleClass();
        Assert.assertEquals(“hello, world”, s.getGreeting());
    }
}
public class SimpleClass {
    public String getGreeting() {
        return “hello, world”;
    }
}

JUnit provides a simple test runner to run your tests. You can run tests at the command line as follows.

neifer@linux-2qs4:~/code/java> java -cp .:junit-4.11.jar:hamcrest-core-1.3.jar org.junit.runner.JUnitCore junit.SimpleTest
JUnit version 4.11
.
Time: 0,005

OK (1 test)

Assert.assertEquals gives an exception, if something is wrong. Most modern IDEs have build-in support for JUnit, of course. If you work with the Microsoft .NET platform, you might use the NUnit framework for unit tests. The annotations are called attributes here, but usage is very similar.

[TestFixture] 
class SimpleTest {
    [Test]
    public void testSimpleClass() {
        SimpleClass s = new SimpleClass();
        Assert.AreEqual(“hello, world”, s.getGreeting());
    }
}
class SimpleClass {
    internal string getGreeting() {
        return “hello, world”;
    }
}

NUnit too provides a simple test runner to run your tests at the command line. A run looks like this.

C:\NUnit>NUnit-2.6.3\bin\nunit-console.exe simpleTest.dll
NUnit-Console version 2.6.3.13283
Copyright (C) 2002-2012 Charlie Poole.
Copyright (C) 2002-2004 James W. Newkirk, Michael C. Two, Alexei A. Vorontsov.
Copyright (C) 2000-2002 Philip Craig.
All Rights Reserved.

Runtime Environment – 
   OS Version: Microsoft Windows NT 6.1.7601 Service Pack 1
  CLR Version: 2.0.50727.5477 ( Net 3.5 )

ProcessModel: Default    DomainUsage: Single
Execution Runtime: net-3.5
.
Tests run: 1, Errors: 0, Failures: 0, Inconclusive: 0, Time: 0,0570119997477751 seconds
  Not run: 0, Invalid: 0, Ignored: 0, Skipped: 0

Advertisements
Unit testing in Java and C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s