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

14 8

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.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay