DEV Community

Cover image for Unit Testing | Full Explanation: C# and .NET
Daniela "Ingeniela" Barazarte
Daniela "Ingeniela" Barazarte

Posted on

Unit Testing | Full Explanation: C# and .NET

Introduction

Hello hello, my name is Daniela Barazarte and I want to welcome you to this complete explanation of unit testing in C# and .NET environment. I'm going to teach you what you need to know, and also what you need to practice.

If you prefer videos, here is a complete tutorial on this topic on YouTube: https://www.youtube.com/watch?v=znzcpBjNqK0

Theory

Logic

"Unit testing"

  • Test: action of testing someone or something to know its qualities, verify its effectiveness, know how it works or reacts, or what result it produces.
  • Unit: consisting of a single unit.

Taking into account the definition of the words separately, you will have a better idea of what it means.

Definition

Unit tests are the tests that we use to test/test small parts of a software system, such as testing/testing methods.

Usage

Example in drawing

If I wanted to test a small part of this whole project, I would have to run the whole solution to test it.... but with unit tests I can test only the unit/part I need to test...

Practice

Task

You have a web application API that has methods to create, read, edit and delete tickets from a train station, the task would be that you need to test that all the methods work correctly.

There are two methods to solve the task:

  1. run the whole solution and test each method individually 2.
  2. Use unit tests, create a script and run it all automatically.

Method: manual testing

  1. I run the whole solution
  2. I open my local server (localhost)
  3. I test each of the methods manually.
  4. I check that it works
  5. I terminate the local server

If I want to do the test again I must repeat the same process, over and over again.

Method: unit testing

  1. I create my unit test project (Add Project > Nunit Test Project)

Nunit Test Project
It will also be important to install 3 Nugets packages (all with the same version):

  • Microsoft.AspNetCore
  • Microsoft.AspNetCore.TestHost
  • Microsoft.EntityFrameworkCore.InMemory
  1. I add the important "Startup" file
public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        public IConfiguration Configuration { get; }
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            // Configure the database context
            services.AddDbContext<TicketMicroserviceContext>(options => options.UseInMemoryDatabase("TicketMicroserviceTest"));

            // Add the transient AppServices that you are going to use
            services.AddTransient<ITicketsAppService, TicketsAppService>();
            services.AddTransient<IRepository<int, Ticket>, Repository<int, Ticket>>();
        }
        public void Configure()
        {
        }
Enter fullscreen mode Exit fullscreen mode
  1. I add the test file and put the whole script:
public class TicketsTest
    {
        protected TestServer server;

        // Add an instance for the test server
    [OneTimeSetUp]
    public void Setup()
    {
        this.server = new TestServer(new WebHostBuilder().UseStartup<Startup>());
    }

    [Order(1)]
    [Test]
    public async Task InsertTicket_Test()
    {
        var _ticketAppService = server.Host.Services.GetService<ITicketsAppService>();

        var addTicket1 = await _ticketAppService.InsertTicketAsync(new TicketDTO() { PassengerId = 1, JourneyId = 1, Seat = 1 });
        var getTicket1 = await _ticketAppService.GetTicketAsync(addTicket1.Id);

        Assert.IsNotNull(addTicket1);
        Assert.AreEqual(addTicket1.PassengerId, getTicket1.PassengerId);
        Assert.AreEqual(addTicket1.JourneyId, getTicket1.JourneyId);
        Assert.AreEqual(addTicket1.Seat, getTicket1.Seat);


        var addTicket2 = await _ticketAppService.InsertTicketAsync(new TicketDTO() { PassengerId = 2, JourneyId = 2, Seat = 2 });
        var getTicket2 = await _ticketAppService.GetTicketAsync(addTicket2.Id);

        Assert.IsNotNull(addTicket2);
        Assert.AreEqual(addTicket2.PassengerId, getTicket2.PassengerId);
        Assert.AreEqual(addTicket2.JourneyId, getTicket2.JourneyId);
        Assert.AreEqual(addTicket2.Seat, getTicket2.Seat);

    }
    [Order(2)]
    [Test]
    public async Task GetAllTickets_Test()
    {
        var _ticketAppService = server.Host.Services.GetService<ITicketsAppService>();

        var insertFirst = await _ticketAppService.InsertTicketAsync(new TicketDTO() { PassengerId = 1, JourneyId = 1, Seat = 1 });
        var insertSecond = await _ticketAppService.InsertTicketAsync(new TicketDTO() { PassengerId = 2, JourneyId = 2, Seat = 2 });
        var insertThird = await _ticketAppService.InsertTicketAsync(new TicketDTO() { PassengerId = 3, JourneyId = 3, Seat = 3 });

        var list = await _ticketAppService.GetTicketsAsync();

        Assert.IsNotNull(list);
        Assert.AreEqual(list.Count, 3);
    }
    [Order(3)]
    [Test]
    public async Task EditTicket_Test()
    {
        var _ticketAppService = server.Host.Services.GetService<ITicketsAppService>();

        var originalTicket = new TicketDTO() { PassengerId = 1, JourneyId = 1, Seat = 1 };
        var insertEntity = await _ticketAppService.InsertTicketAsync(originalTicket);

        var editedTicket = new Ticket() { Id = insertEntity.Id, PassengerId = 2, JourneyId = 2, Seat = 2 };
        var updateEntity = await _ticketAppService.EditTicketAsync(editedTicket);

        var checkUpdate = await _ticketAppService.GetTicketAsync(insertEntity.Id);

        Assert.IsNotNull(originalTicket);
        Assert.AreNotEqual(originalTicket.PassengerId, checkUpdate.PassengerId);
        Assert.AreNotEqual(originalTicket.JourneyId, checkUpdate.JourneyId);
        Assert.AreNotEqual(originalTicket.Seat, checkUpdate.Seat);
    }
    [Order(4)]
    [Test]
    public async Task DeleteTicket_Test()
    {
        var _ticketAppService = server.Host.Services.GetService<ITicketsAppService>();

        var addTicket = await _ticketAppService.InsertTicketAsync(new TicketDTO() { PassengerId = 1, JourneyId = 1, Seat = 1 });

        await _ticketAppService.DeleteTicketAsync(addTicket.Id);
        var checkDelete = await _ticketAppService.GetTicketAsync(addTicket.Id);

        Assert.IsNull(checkDelete);
    }
Enter fullscreen mode Exit fullscreen mode
  1. I run the complete script

Maybe it took me longer to create the unit test project from scratch, but if I want to test the script several more times it will be easier and faster.

Conclusion

Unit tests: Improve the quality of the software

  • Improve software quality
  • Reduce development time
  • Make debugging much easier
  • Give more confidence to the code

Acknowledgement

Thank you very much for reading, if you have any questions you can comment, you can also find me on my other networks like Twitter, GitHub and LinkedIn

Top comments (0)