Getting Started with xUnit .net Core , Visual Studio

Describing the difference between facts and theories, we like to say:

Theories are tests which are only true for a particular set of data.

Facts are tests which are always true. They test invariant conditions.

A good example of this testing numeric algorithms. Let’s say you want to test an algorithm which determines whether a number is prime or not. If you’re writing the positive-side tests (non prime numbers), then feeding prime numbers into the test would cause it fail, and not because the test or algorithm is wrong.

Let’s add a theory to our existing facts (including a bit of bad data, so we can see it fail):

using Xunit;
using Prime.Services;

namespace Prime.UnitTests.Services
{
    public class PrimeService_IsPrimeShould
    {
        private readonly PrimeService _primeService;

        public PrimeService_IsPrimeShould()
        {
            _primeService = new PrimeService();
        }

        [Fact]
        public void IsPrime_InputIs1_ReturnFalse()
        {
            var result = _primeService.IsPrime(1);

            Assert.False(result, "1 should not be prime");
        }
    }
}

The [Fact] attribute declares a test method that’s run by the test runner. From the PrimeService.Tests folder, run dotnet test. The dotnet test command builds both projects and runs the tests. The xUnit test runner contains the program entry point to run the tests. dotnet test starts the test runner using the unit test project.

Add more tests

Add prime number tests for 0 and -1. You could copy the preceding test and change the following code to use 0 and -1.

Copying test code when only a parameter changes results in code duplication and test bloat. The following xUnit attributes enable writing a suite of similar tests.

  • [Theory] represents a suite of tests that execute the same code but have different input arguments.
  • [InlineData] attribute specifies values for those inputs.

Rather than creating new tests, apply the preceding xUnit attributes to create a single theory. Replace the following code:

[Theory]
[InlineData(-1)]
[InlineData(0)]
[InlineData(1)]
public void IsPrime_ValuesLessThan2_ReturnFalse(int value)
{
    var result = _primeService.IsPrime(value);

    Assert.False(result, $"{value} should not be prime");
}

In the preceding code, [Theory] and [InlineData] enable testing several values less than two. Two is the smallest prime number.

Published by codeblogforfun

Coder, blogger, traveler

Leave a comment

Design a site like this with WordPress.com
Get started