My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

Using Dependency Injection in Units and Integrations Tests

Eliezer Bwana's photo
Eliezer Bwana
·Dec 27, 2021·

3 min read

Hello everyone, after a long period without publishing an article, today I'm back with this one. I will like to share with you a little thing about Unit Tests, on how to use dependency injection in our test.

We always use direct instantiation in our test when we want to test some stuff, but it can be kind our boring to always do that when you have more classes or services to, functionality to test it's can be very tiring and hard. to solve that problem it's very helpful to use dependency injection in our test so we can avoid repeated code.

What's dependency Injection

Dependency Injection is one of the most known techniques that help you to create more maintainable code. It's a design pattern to implement Inversion of Control. It allows you to inject the concrete implementation of a low-level component into a high-level component.

To simplify, Dependency Injection helps you to reduce High coupling code and reduce the number of times you initialize classes. the most used type of dependency injection is the dependency injection by the constructor. to use it in asp.net core it's required to register the interface and its implementation(concrete class) in the IoC container. Then when injected in the constructor the IoC container will search(scan) assembly to find the concrete class of the called interface, the uses the methods. for maintainability is good to have interfaces and class which implement the interface.

Implementation

For the practice part (implementation) we will be using a sample project on .Net 6, Web API project(minimal API) to stay simple. so let go. in the API project, we will create a folder name Core in which we will put two folders, Interfaces and Services. In the interfaces folder, I will add an interface name "IGreetingServices" with Just one Method signature, "Greet". In the services folder, I will create a class named "GreetingService" which will inherit from the IGreetingServices interfaces, as shown below.

namespace WebApi.Core.Interfaces
{
    public interface IGreetingService
    {
        string  Greet(string name);
    }
}
using WebApi.Core.Interfaces;

namespace WebApi.Core.Services
{
    public class GreetingService : IGreetingService
    {
        public GreetingService()
        {

        }
        public string Greet(string name) => $"Hello {name} and happy marry christmass and 
                                                                        happy new  year!";
    }
}

Now we will add the test project, NUnit template from VS2020 and .Net 6, add the API project reference to the test project. In order to use our services in this newly created test project, we need to add this NuGet package to our test project.

using NUnit.Extension.DependencyInjection;
using NUnit.Extension.DependencyInjection.Abstractions;
using NUnit.Extension.DependencyInjection.Unity;

After downloading those packages, we will implement our Ioc Container register for Unity Ioc. Create a class in the Test project name it as you want. In my case, i named it "IOC" and configure it as shown below.

using NUnit.Extension.DependencyInjection;
using NUnit.Extension.DependencyInjection.Abstractions;
using NUnit.Extension.DependencyInjection.Unity;
using Unity;
using WebApi.Core.Interfaces;
using WebApi.Core.Services;


[assembly: NUnitTypeInjectionFactory(typeof(UnityInjectionFactory))]//Tell the extension that we will be using the Microsoft Unity Injection factory;
[assembly: NUnitTypeDiscoverer(typeof(IocRegistrarTypeDiscoverer))]//this tells the extension to scan for the implementation(concrete classes)
namespace DIUnitTest
{
    public class IOC : RegistrarBase<IUnityContainer>
    {
        protected override void RegisterInternal(IUnityContainer container)
        {
            container.RegisterType<IGreetingService, GreetingService>();//Register our services
        }
    }
}

Using the services in the test

So now we will use the classic constructor dependency injection and call methods. As shown below.

using NUnit.Framework;
using WebApi.Core.Interfaces;

namespace DIUnitTest
{
    [NUnit.Extension.DependencyInjection.DependencyInjectingTestFixture]
    public class Tests
    {
        private readonly IGreetingService _greetingService;
        public Tests(IGreetingService greetingService)
        {
            _greetingService = greetingService;
        }

        [SetUp]
        public void Setup()
        {
        }

        [Test]
        public void Test1()
        {
            var greetingFromApi = _greetingService.Greet("John Doe");
            Assert.IsNotNull(greetingFromApi);
        }

        [Test]
        public void Test2()
        {
            Assert.IsInstanceOf<string>(_greetingService.Greet("John Doe"));
        }
    }
}

Voila, here we are. thank you for reading it.