DEV Community

Cover image for From TDD to DDD: Building a .NET Core Web API - Part 2
LUCIANO DE SOUSA PEREIRA
LUCIANO DE SOUSA PEREIRA

Posted on

From TDD to DDD: Building a .NET Core Web API - Part 2

The complete project can be found here: https://github.com/lucianopereira86/CRUD-NetCore-TDD

Technologies

Topics

Test Project

It's time to begin the fun!

We will build tests for each CRUD method of the User entity by using Entity Framework Core structure.
There will be two types of unit tests: Fact and Theory.

Fact is a method with a unique result without parameters.

Theory allow multiple parameters expecting for different results.

Post User

Add a folder named "Tests" to the Test Project with a file named "PostUserTest.cs" with the code below:

using Xunit;

namespace CRUD_NETCore_TDD.Test.Tests
{
    public class PostUserTest
    {
        #region THEORY
        #endregion
        #region FACT
        [Fact]
        public void Fact_PostUser ()
        {

        }
        #endregion
    }
}

Fact

Red Step

Our first test will run what we really want: to register a new user to the database. Write this code inside the Fact_PostUser method:

[Fact]
public void Fact_PostUser ()
{
    // EXAMPLE
    var user = new User("LUCIANO PEREIRA", 33, true);

    // REPOSITORY
    ctx.User.Add(user);
    ctx.SaveChanges();

    // ASSERT
    Assert.Equal(1, user.Id);
}

At first, there are no User class. Also, the "ctx" object should be an instance of the DbContext class, but there is no EF Core library installed yet to make the code to compile.
That is the Red step. We know what we want and what we have to do.

Before going to the Green step, change the method's name from "Fact_PostUser" to "Fact_PostUser_NoModelNoRepository", so it becomes clear what is missing for the method to run.

Next

Let's implement the Green step.

Top comments (0)