Created
October 11, 2021 17:57
-
-
Save eramax/1a9ad0f72d67b9323fd22a0cf1478f84 to your computer and use it in GitHub Desktop.
Clean mocking for unit tests using NSubstitute in .NET
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 NSubstitute; | |
using NSubstitute.ReturnsExtensions; | |
using WebApi2.Models; | |
using WebApi2.Services; | |
using Xunit; | |
/// <summary> | |
/// Clean mocking for unit tests using NSubstitute in .NET (Core, Framework, Standard) | |
/// https://www.youtube.com/watch?v=LcQYv0cBWk0& | |
/// </summary> | |
namespace NSub | |
{ | |
public class UserServiceTests | |
{ | |
private readonly IUserService service; | |
private readonly IGenericRepository<User> repo = Substitute.For<IGenericRepository<User>>(); | |
public UserServiceTests() | |
{ | |
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 | |
Assert.Equal(user.Id, result.Id); | |
Assert.Equal(user.Name, result.Name); | |
} | |
[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 | |
Assert.Null(result); | |
} | |
[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(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment