Som jag nämnde i mitt senaste inlägg
Assert.AreEqual(1000.0, order.TotalAmount());
Istället vill vi få till en läsbar verifering enligt följande:
nBehave har en bra klass med extension methods att utgå ifrån. S#arp Architecture
public static void ShouldEqualSqlDate(this DateTime actual, DateTime expected)
{
TimeSpan timeSpan = actual – expected;
Assert.Less(Math.Abs(timeSpan.TotalMilliseconds), 3);
}
public static void ShouldContainErrorMessage(this Exception exception, string expected){
StringAssert.Contains(expected, exception.Message);
}
using NUnit.Framework;
namespace ExtensionMethods
{
public static class TestExtensions
{
public static void ShouldEqualRoundedValue(this double
actual, double expected)
{
// 0.005 är deltat
Assert.AreEqual(expected, actual, 0.005);
}
}
}
Självklart ska vi även testa våra egna veriferingsmetoder:
using NUnit.Framework;
namespace ExtensionMethods
{
[TestFixture]
public class ShouldEqualRoundedValueTests
{
[Test]
public void CanRoundCorrectWhenRoundingDown()
{
const double amount = 100.124;
amount.ShouldEqualRoundedValue(100.12);
}
[Test]
public void CanRoundCorrectWhenRoundingUp()
{
const double amount = 100.126;
amount.ShouldEqualRoundedValue(100.13);
}
[Test]
public void CanRoundCorrectWhenInBetween()
{
const double amount = 100.125;
amount.ShouldEqualRoundedValue(100.13);
[Test]
public void CanRoundAmountCorrectWhenAssertFails()
{
const double amount = 100.125;
try
{
amount.ShouldEqualRoundedValue(100.14);
Assert.Fail(”The test should fail!”);
}
catch (AssertionException exc)
Assert.AreNotEqual(”The test should fail!”,
exc.Message);
}
}
}
}
Snygg och enkel verifiering!






















