The complete project can be found here: https://github.com/lucianopereira86/CRUD-NetCore-TDD
Technologies
- Visual Studio 2019
- .NET Core 3.1.0
- xUnit 2.4.0
- Microsoft.EntityFrameworkCore 3.1.0
- FluentValidation 8.6.0
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)