《Pragmatic Unit Testing in C#》-Part1

  1. Classic Asserts

Asserts are the fundamental building block for unit tests; the NUnit library provides a number of different forms of assert as static methods in the Assert class.

AreEqual

Assert.AreEqual(expected, actual [, string message])

Assert.AreEqual(expected, actual, tolerance [, string message])

Less / Greater

Assert.Less(x, y)

Assert.Greater(x,y)

GreaterOrEqual / LessOrEqual

Assert.GreaterOrEqual(x, y)

Assert.LessOrEqual(x,y) 

IsNull / IsNotNull

Assert.IsNull(object [, string message])

Assert.IsNotNull(object [, string message]) 

AreSame

Assert.AreSame(expected, actual [, string message])

IsTrue

Assert.IsTrue(bool condition [, string message])

Assert.IsFalse(bool condition [, string message])

Fail

Assert.Fail([string message])

 

2. Constraint-based Asserts

Is.EqualTo

Assert.That(actual, Is.EqualTo(expected))

Assert.That(actual, new EqualConstraint(expected)) 

Here is one called Within() that is equivalant to our same example that used the classic-style in the previous section.

Assert.That(10.0/3.0, Is.EqualTo(3.33).Within(0.01f));

Is.Not.EqualTo

Assert.That(actual, Is.Not.EqualTo(expected)) 

Assert.That(actual, new NotConstraint(new EqualConstraint(expected))); 

Is.AtMost 

Assert.That(actual, Is.AtMost(expected)) 

Is.Null

Assert.That(expected, Is.Null);

Assert.That(expected, Is.Not.Null);

Assert.That(expected, !Is.Null);

Is.Empty

Assert.That(expected, Is.Empty);

Is.AtLeast

Assert.That(actual, Is.AtLeast(expected));

Is.InstanceOfType

Assert.That(actual, Is.InstanceOfType(expected));

Has.Length

Assert.That(actual, Has.Length(expected));

 

 3.  More NUnit Asserts 

List.Contains

Assert.That(actualCollection, List.Contains(expectedValue))

Assert.That({5, 3, 2}, List.Contains(2))

Is.SubsetOf

Assert.That(actualCollection, Is.SubsetOf(expectedCollection))

Assert.That(new byte[] {5, 3, 2}, Is.SubsetOf(new byte[] {1, 2, 3, 4, 5}))

Text.StartsWith

Assert.That(actual, Text.StartsWith(expected))

Assert.That("header:data.", Text.StartsWith("header:"))

Assert.That("header:data.", Text.StartsWith("HeadeR").IgnoreCase)

Text.Matches

Assert.That(actual, Text.Matches(expected))

Assert.That("header:data.", Text.Matches("$header^\."))

FileAssert.AreEqual / AreNotEqual

FileAssert.AreEqual(FileInfo expected, FileInfo actual)

FileAssert.AreEqual(String pathToExpected, String pathToActual)

Test whether two files are the same, byte for byte. Note that if we do the work of opening a Stream (file-based, or not), we can use the EqualsConstraint instead, like so:

Stream expectedStream = File.OpenRead("expected.bin");

Stream actualStream = File.OpenRead("actual.bin");

Assert.That(actualStream, Is.EqualTo(expectedStream)); 

 

 

 

 

你可能感兴趣的:(unit test)