Testing with NUnit

To use the NUnit testing framework within a .Net project we have to create a normal Class Library Project (not a Unit Test Project, that is for the UnitTest Framework). Then we can add NUnit to the project via NuGet to start writing tests.

To write a test we have to create a class in the same way we do with UnitTest. NUnit offers some interesting functionality, such as the SetUp/TearDown methods, executed before/after each test, the possibility to have parametrized methods, and so on.

Here is an example in which we are testing an object who represent a range between two points and calculate its length:

//Additional NS
using NUnit.Framework;
using ProvaNUnit;
namespace MyTestLibrary
    public class MyRangeModelTest
        public class Given_A_MyRangeModel
            private MyRangeModel _model;
            //The SetUp method will be
            //executed before each test
            public void SetUp()
                _model = new MyRangeModel
                    Point1 = 2,
                    Point2 = 10
            //This is a test
            public void It_Should_Calculate_The_Length()
                Assert.AreEqual(_model.RangeLength, 8);
            //This is a parametrized test. It will
            //be executed for each parameters set
            [TestCase(3, 8, TestName = "With_A_Forward_Range")]
            [TestCase(8, 3, TestName = "With_A_Backward_Range")]
            [TestCase(5, 5, TestName = "With_A_Empty_Range")]
            public void It_Should_Calculate_More_Lengths(int point1, int point2)
                _model.Point1 = point1;
                _model.Point2 = point2;
                Assert.AreEqual(_model.RangeLength, Math.Abs(point2 - point1));
            //The TearDown method will be
            //executed after each test
            public void TearDown()
                _model = null;

I can run NUnit tests directly from VS with Resharper. I can run a single test or the entire test set by right-clicking on the text editor. The results will be displayed in both the text editor and the Resharper Unit Test window.


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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s