All About xUnit
Assertions
In every assert you indicate the value you expect.
NUnit and MSTest will compare it to the actual value from the code under test.
The code in the tabs below shows how to assert information about various types.These assertions are the same in NUnit and MSTest. We're using NUnit's [Test] attribute in these examples;
in MSTest, you would use the [TestMethod] attribute above the method declaration.NUnit and MSTest will compare it to the actual value from the code under test.
Check that two
object
s are equal:
[Test]
public void StringEquality()
{
string expected = "Something";
string actual = "Something";
Assert.AreEqual(expected, actual);
}
Know that: This assert invokes the objects' Equals
method (defined on them, or inherited from object
, as the case may be).
Check that two integers are equal:
[Test]
public void IntEquality()
{
int expected = 10;
int actual = 10;
Assert.AreEqual(expected, actual);
}
Due to their internal representation, it is tricky to say when two
float
s or two double
s are equal.
The canonical solution is to assert equality to within a certain precision, or tolerance:
[Test]
public void DoubleEquality()
{
double expected = 10.01;
double actual = 10.01;
double precision = 0.000001;
Assert.AreEqual(expected, actual, precision);
}[Test]
public void FloatEquality()
{
float expected = 10.0001F;
float actual = 10.00009F;
float precision = 0.0001F;
Assert.AreEqual(expected, actual, precision, "floats approximately equal");
}
Check that
object
references (like String
or StringBuilder
) point to
the same object, or they are null
/not null
.
[Test]
public void ObjectsSame()
{
object anObject = new object();
object sameObject = anObject;
Assert.AreSame(anObject, sameObject);
}[Test]
public void ObjectsNotSame()
{
object anObject = new object();
object anotherObject = new object();
Assert.AreNotSame(anObject, anotherObject);
}[Test]
public void NonNullObject()
{
string anObject = "hello";
Assert.IsNotNull(anObject);
}[Test]
public void NullObject()
{
string anObject = null;
Assert.IsNull(anObject);
}
Check that a Boolean expression is true or false:
[Test]
public void BooleanTrue()
{
bool result = true;
Assert.IsTrue(result);
}[Test]
public void BooleanFalse()
{
bool result = false;
Assert.IsFalse(result);
}
(Reading...)
Formatting Hints:
To format... | use this markup: |
---|---|
source code | {source:lang=java|lineNumbers=false}...{source} (Supported languages: java, cpp, csharp, c, python.) |
bold text | __some text__ |
italicized text | ~~some text~~ |
underlined text | @@some text@@ |
a method or class name | ``myMethod(...)`` |