Unit Testing/xUnit.net/Test Exceptions
Create a C# Program
editCreate the following C# program. Save it as Multiply.cs
public class Multiply
{
public double MultiplyValues(double x, double y)
{
return x * y;
}
public string MultiplyValues(string text, int count)
{
if (count < 0)
{
throw new System.ArgumentException(
"count must be greater than or equal to zero");
}
var result = new System.Text.StringBuilder().Insert(0, text, count).ToString();
return result;
}
}
Create a Test Program
editCreate the following C# test program. Save it as MultiplyTest.cs
using Xunit;
public class UnitTest
{
[Fact]
public void Multiply2x2Test()
{
var multiply = new Multiply();
var result = multiply.MultiplyValues(2, 2);
Assert.Equal(4, result);
}
[Fact]
public void MultiplyStringx2Test()
{
var multiply = new Multiply();
var result = multiply.MultiplyValues("test", 2);
Assert.Equal("testtest", result);
}
[Fact]
public void MultiplyStringTrowsExceptionTest()
{
var multiply = new Multiply();
Assert.Throws<System.ArgumentException>(() =>
multiply.MultiplyValues("test", -1)
);
}
}
Test Success
editTest the program by running it in a terminal or command prompt in the same folder as the project above and observe the results.
dotnet test
Test Failure
editChange the multiply source code somehow, such as multiplying the string by a positive number. Test the program by running Jest again and observe the results.