3. Semantic test assertion
Use Assert.That to test whether conditions are true.
Read time 2 minutesLast updated 13 days ago
Learning objectives
This exercise introduces the and related classes.
Assert.ThatIntro and motivation
The NUnit test framework and the Unity Test Framework have a series of classes for asserting objects in a way that is closer to natural language. This makes the statements easily readable.
Here are some examples on how to use the semantic assertion classes:
Assert.That(myValue, Is.GreaterThan(20));Assert.That(str, Does.Contain("a string").And.Contain("something else"));
Here we check that the variable is greater than 20 and then that the string contains both "a string" and "something else".
myValuestrThe semantic assertion is also known as Constraint Model. Other than and there are multiple other keywords that can be used.
ItDoesExercise
In the sample, there is a class called , which returns values of different types.
3_SemanticTestAssertionValueOutputterWrite tests that assert on the different outputs. It should be verified that:
- returns 11.
GetInt() - returns a string that contains the words
GetString()andstring.asserted - returns a value that is around 19.33.
GetFloat()
Hints
- Asserting on the float might require a check for the value being greater than 19.33 and less than 19.34, as the output is not rational.
Solution
A full solution to the exercise is available in the sample .
3_SemanticTestAssertion_Solutioninternal class ValueOutputterTests{ [Test] public void GivesExpectedInt() { var outputterUnderTest = new ValueOutputter(); var number = outputterUnderTest.GetInt(); Assert.That(number, Is.EqualTo(11)); } [Test] public void GivesExpectedString() { var outputterUnderTest = new ValueOutputter(); var str = outputterUnderTest.GetString(); Assert.That(str, Does.Contain("string").And.Contain("asserted")); } [Test] public void GivesExpectedFloat() { var outputterUnderTest = new ValueOutputter(); var number = outputterUnderTest.GetFloat(); Assert.That(number, Is.GreaterThan(19.33f).And.LessThan(19.34f)); }}