Unit testing with NUnit

Install from Nuget 3.12.0, the Mock references below are from Moq and the example’s Unit Of Work is SomeMethod.

Assert.AreEqual

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
using Moq;
using NUnit.Framework;

[TestFixture]
public class MyClassTest
{
private Mock<ISomeService> _someServiceMock;

[SetUp]
public void SetUp()
{
_someServiceMock = new Mock<ISomeService>();
}

[Test]
public void SomeMethod_initialCondition_expectedResult()
{
// Arrange
var expected = "hoe";

_someServiceMock
.Setup(x => x.SomeServiceMethod(someValue))
.Returns(true);

var classUnderTest = new MyClass(_someServiceMock.Object);

// Act
var actual = classUnderTest.SomeMethod(..parms);

// Assert
Assert.AreEqual(expected, actual);
}
}

Assert.Throws

Assert type of MyException was thrown.

1
2
// Assert
Assert.Throws<MyException>(() => classUnderTest.SomeMethod(paramValue1, paramValue2));

.Verify

Assert a method in the mocked service was called once.

1
2
3
4
// Assert
_someServiceMock.Verify(
x => x.SomeOtherServiceMethod(paramValue1),
Times.Once());

TestCase

Pass parameters to a test

1
2
3
4
[TestCase(-1, "hoe")]
[TestCase(42, "foo")]
public void SomeMethod_initialCondition_expectedResult(int someId, string someText)
{ ... }

TestCaseSource

Pass the test an array of data.

1
2
3
4
5
6
7
8
9
10
11
[TestCaseSource("GetSweetData")]
public void SomeMethod_initial_condition_expected_result(int someId, string someText)
{

}

static readonly object[] GetSweetData = new List<object>()
{
new object[]{ 123, "Some Data" },
new object[]{ 456, "Some Other Data" },
}.ToArray();

References