DEV Community

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

Posted on

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

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

Technologies

Post User • Fact

Refactor Step

We will concentrate the database operations inside a repository class for the user entity.

Firstly, modify the "Fact_PostUser" method like this:

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

    // REPOSITORY
    user = new UserRepository(ctx).Post(user);

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

As you can see, it must be created a "UserRepository" class with a "Post" method that must execute that same operations from before.

Inside the Infra project, create another file inside the "Repositories" folder named "UserRepository.cs" with the following code:

using CRUD_NETCore_TDD.Infra.Models;

namespace CRUD_NETCore_TDD.Infra.Repositories
{
    public class UserRepository
    {
        private readonly MyContext ctx;
        public UserRepository(MyContext ctx)
        {
            this.ctx = ctx;
        }
        public User Post(User user)
        {
            ctx.User.Add(user);
            ctx.SaveChanges();
            return user;
        }
    }
}

Just import the "UserRepository" class inside the "PostUserTest" file and it will compile.

Run the test again:

print07

Our refactoring is complete!

If you have followed the instructions faithfully until here, then your project must be like this:

print08

Next

We are still far from finishing the POST tests. It's necessary to validate the user attributes before persist them in the database, so let's create our first Theory.

Top comments (0)