Unit Tests Code coverage

Unittests-mstest

Unit test example

using Microsoft.VisualStudio.TestTools.UnitTesting;
using Prime.Services;

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

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

        [TestMethod]
        public void ReturnFalseGivenValueOf1()
        {
            var result = _primeService.IsPrime(1);

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

Using Mock object created wih 'moq'

Moq is a framework that allow you to mock objects - If the method you want to test needs an object you can create a mock object. The idea is that you create a 'fake' object and tell it what to return when porperties or method are used

using Microsoft.VisualStudio.TestTools.UnitTesting;
using MSTestMoqExample;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Moq;

namespace MSTestMoqExample.Tests
{
    [TestClass()]
    public class PersonHelperTests
    {
        private PersonHelper helper;

        [TestInitialize]
        public void Startup()
        {
            helper = new PersonHelper();
        }

        [TestMethod()]
        public void getCurrentYearTest()
        {
            Assert.AreEqual(helper.getCurrentYear(), 2019);
        }

        [TestMethod()]
        public void calculateAgeTest()
        {
            // create m mock object that can act as a person object
            var mockPerson = new Mock<IPerson>();
            // setup a a property on the mock object
            mockPerson.SetupGet(p => p.BirthYear).Returns(1975);

            Assert.IsTrue(helper.calculateAge(mockPerson.Object) == 44);
        }

        [TestMethod()]
        public void isMaleTest()
        {
            var mockPerson = new Mock<IPerson>();
            mockPerson.Setup(p => p.GetGender()).Returns(Person.Gender.male);

            Assert.IsTrue(helper.isMale(mockPerson.Object));
        }

    }
}

Learn to how to use moq here: The example on github https://github.com/Moq/moq4/wiki/Quickstart

Unit test links: