.Net Core Unit Test with resolve service dependency


Introduction

In this article will see, how to make a unit test in .net core 2.2. also how to use dependency injection.

Previous Article  

Before we start anything, please have a look at this article. Click here.

Service Test

Now focus on the main point. At first create a new NUnitTest(.Net Core 2.2) project and name it NUnitTestProject. Here we are using NUnitTest framework for the unit test.



After that create a new Class into NUnitTestProject and name it Startup and put the following code in it.
using DI;
using Microsoft.Extensions.DependencyInjection;
using NUnit.Framework;
using System;
 
namespace NUnitTestProject
{
    [SetUpFixture]
    public class Startup
    {
        internal static IServiceProvider ServiceProvider { get; set; }
        [OneTimeSetUp]
        public void RunBeforeAnyTests()
        {
            ServiceProvider = ContainerBuilder();
        }
        [OneTimeTearDown]
        public void RunAfterAnyTests()
        {
 
        }
        public IServiceProvider ContainerBuilder()
        {
            IServiceCollection services = new ServiceCollection();
            services.BuildServiceContainer();
            return services.BuildServiceProvider();
        }
 
    }
}

Let's talk about Startup class. Here we can see there are three methods. The first method name is RunBeforeAnyTests. When this project will run at first this RunBeforeAnyTests() method will execute. Next method name is RunAfterAnyTests, this method will execute lastly. Next method name is ContainerBuilder, this method returning our Service Container.

We declare a ServiceProvider variable, also it has get set property. We can see variable is static and its access label is internal. ServiceProvider variable will store our service container and it will help us to control our Dependency. Look at the method RunBeforeAnyTests, here we set our container in the ServiceProvider variable. That means when we run our unit test, at first all services set into ServiceProvider Variable. Now go to the UnitTest1.cs class and put the following code in it.
using DAL.Interface;
using NUnit.Framework;
using Microsoft.Extensions.DependencyInjection;
 
namespace NUnitTestProject
{
    public class Tests
    {
        private IValueRepository _valueRepository;
 
        [SetUp]
        public void Setup()
        {
            var serviceProvider = Startup.ServiceProvider;
            if (serviceProvider != null)
            {
                _valueRepository = serviceProvider.GetService<IValueRepository>();
 
            }
        }
 
        [Test]
        public void ValueRepository_Test()
        {
            var actualResult = _valueRepository.GetValues();
            var expectedResult = new string[] { "valueFromRepository1", "valueFromRepository2" };
            Assert.AreEqual(expectedResult, actualResult);//Chill
        }
    }
}

Here we can see in the Setup method called our ServiceProvider variable. See how we get our dependency.

_valueRepository = serviceProvider.GetService<IValueRepository>();

This way we can resolve our dependency.

Now, look at the ValueRepository_Test() test method. Inside this test method, we call IValueRepository. This way we can call our services. Now run the test cases. If you cannot see the Test Explorer tab, then go to the Test -> Windows -> Test Explorer. Now press Run all.



See the result.


The test case passed. Here we tested our service. Let’s test our controller.

Controller Test

At first, right-click on the NUnitTestProject project and go to the Dependencies -> Add References.


And select CoreDI project and press OK button. Now go to the UnitTest1.cs file. And declare ValuesController as _valuesController.

private ValuesController _valuesController;

Next, in the setup method create ValuesController object.

_valuesController = new ValuesController(_valueRepository);

Next, create a test method and name it ValuesController_test and put the following code in it.
[Test]
    public void ValuesController_test()
    {
        var actualResult = _valuesController.ChillMethod().Value;
        var expectedResult = new string[] { "valueFromRepository1", "valueFromRepository2" };
        Assert.AreEqual(expectedResult, actualResult);
    }

Now I am sharing the full UnitTest1.cs source code. Please check it.
using DAL.Interface;
using NUnit.Framework;
using Microsoft.Extensions.DependencyInjection;
using CoreDI.Controllers;
 
namespace NUnitTestProject
{
    public class Tests
    {
        private IValueRepository _valueRepository;
        private ValuesController _valuesController;
 
        [SetUp]
        public void Setup()
        {
            var serviceProvider = Startup.ServiceProvider;
            if (serviceProvider != null)
            {
                _valueRepository = serviceProvider.GetService<IValueRepository>();
                _valuesController = new ValuesController(_valueRepository);
 
            }
        }
 
        [Test]
        public void ValueRepository_Test()
        {
            var actualResult = _valueRepository.GetValues();
            var expectedResult = new string[] { "valueFromRepository1", "valueFromRepository2" };
            Assert.AreEqual(expectedResult, actualResult);
        }
        [Test]
        public void ValuesController_test()
        {
            var actualResult = _valuesController.ChillMethod().Value;
            var expectedResult = new string[] { "valueFromRepository1", "valueFromRepository2" };
            Assert.AreEqual(expectedResult, actualResult);
        }
    }
}

Now test our ValuesController_test method. So in the Test Explorer tab press Run All


See the result. All test method passed the unit test.

Conclusion 

We have successfully test our service and controllers. I the large project we have so many controllers and services. This way, we can resolve our service dependencies.

Source Code

Get the source code from GitHub

Post a Comment

0 Comments