LUCIANO DE SOUSA PEREIRA
Posted on December 16, 2019
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 • Theory
Red Step • Age
Let's do a Theory for the "Age" attribute.
[Theory]
[InlineData(0, 102)]
[InlineData(-1, 102)]
[InlineData(33, 102)]
public void Theory_PostUser_Age(int Age, int ErrorCode)
{
var user = new User
{
Age = Age
};
CheckError(new PostUserValidator(), ErrorCode, user);
}
If you run the tests, there will error for all the values because we have not implemented the validation for the age yet. It must be greater than zero.
Green Step • Age
Inside the PostUserValidators constructor, add the following lines:
public PostUserValidator()
{
RuleFor(x => x.Name)
.Cascade(CascadeMode.StopOnFirstFailure)
.NotEmpty()
.WithErrorCode("100")
.MaximumLength(20)
.WithErrorCode("101");
RuleFor(x => x.Age)
.Cascade(CascadeMode.StopOnFirstFailure)
.GreaterThan(0)
.WithErrorCode("102");
}
Run the tests again and this will be the result:
Only the valid value (33) has not returned any error, so our tests are working correctly again!
Post User • Fact II
Refactor Step II
There is no need for another Theory for the "PostUserTest" but another Fact is required to validate the data. Rename the "Fact_PostUser" method to "Fact_PostUser_NoValidation" and create another one:
[Fact]
public void Fact_PostUser()
{
// EXAMPLE
var user = new User(0, "LUCIANO PEREIRA", 33, true);
var val = new PostUserValidator().Validate(user);
// ASSERT
Assert.True(val.IsValid);
if (val.IsValid)
{
// REPOSITORY
user = new UserRepository(ctx).Post(user);
// ASSERT
Assert.Equal(1, user.Id);
}
}
This time we are using the "Assert" class to ensure that the validation will be true before accessing the repository. Run the test again.
This must be your project so far:
Coming soon...
The PUT method will be the next to receive tests, repository and validation.
Posted on December 16, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.