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
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:
Our refactoring is complete!
If you have followed the instructions faithfully until here, then your project must be like this:
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)