Created
October 11, 2021 19:19
-
-
Save eramax/a33498a0f61cb8d6c2c58579f50a4733 to your computer and use it in GitHub Desktop.
How to write cleaner unit tests with Fluent Assertions in .NET Core
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using DataLib; | |
using FluentAssertions; | |
using NSubstitute; | |
using NSubstitute.ReturnsExtensions; | |
using System; | |
using WebApi2.Models; | |
using WebApi2.Services; | |
using Xunit; | |
/// <summary> | |
/// How to write cleaner unit tests with Fluent Assertions in .NET Core | |
/// https://www.youtube.com/watch?v=b2zxl5zNjlA | |
/// </summary> | |
namespace NSub | |
{ | |
public class UserServiceTestsFluent | |
{ | |
private readonly IUserService service; | |
private readonly IGenericRepository<User> repo = Substitute.For<IGenericRepository<User>>(); | |
public UserServiceTestsFluent() | |
{ | |
service = new UserService(repo); | |
} | |
[Fact] | |
public void GetUserById_should_return_a_user() | |
{ | |
// Arrange | |
var user = new User { Id = 100, Email = "email", Name = "Ahmed", Password = "123", Username = "ahmed" }; | |
repo.GetById(user.Id).Returns(user); | |
// ACT | |
var result = service.Get(user.Id); | |
// Assert | |
result.Should().Be(user); | |
result.Email.Should().StartWith(user.Email); | |
} | |
[Fact] | |
public void GetUserById_should_return_null_whenUserDoesNotExist() | |
{ | |
// Arrange | |
var user = new User { Id = 100, Email = "email", Name = "Ahmed", Password = "123", Username = "ahmed" }; | |
repo.GetById(Arg.Any<int>()).ReturnsNull(); | |
// ACT | |
var result = service.Get(user.Id); | |
// Assert | |
result.Should().BeNull(); | |
} | |
[Fact] | |
public void GetUserById_Remove_User() | |
{ | |
// Arrange | |
var user = new User { Id = 100, Email = "email", Name = "Ahmed", Password = "123", Username = "ahmed" }; | |
var user2 = new User { Id = 200, Email = "email", Name = "Ahmed", Password = "123", Username = "ahmed" }; | |
repo.GetById(Arg.Any<int>()).Returns(user); | |
// ACT | |
service.Remove(user); | |
// Assert | |
repo.Received(1).Remove(user); | |
repo.Received(1).Remove(Arg.Any<User>()); | |
repo.DidNotReceive().Remove(user2); | |
repo.Received(1).Save(); | |
} | |
[Theory] | |
[InlineData(10,0)] | |
[InlineData(10, 1)] | |
public void MathDivide(int a, int b) | |
{ | |
// Arrange | |
Action div = () => { _ = a / b; }; | |
// ACT | |
// Assert | |
div.Should().Throw<DivideByZeroException>().WithMessage("Attempted to divide by zero."); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment