我想测试我的无效存储库。我的服务班是这样的。
public class AccountService
{
private readonly IAccountRepository accountRepository;
public AccountService(IAccountRepository accountRepository)
{
this.accountRepository = accountRepository;
}
public User GetById(string userId)
{
User user = accountRepository.GetById(userId);
if (user == null)
throw new UserNotFoundException();
return user;
}
public void Add(User user)
{
accountRepository.Add(user);
}
}
在我的测试类中,我创建了一个使用 FakeItEasy 工具的假存储库。
[TestFixture]
public class AccountServiceTests
{
private IAccountRepository repository;
private AccountService service;
private string ValidUserId = "aaa";
private string InvalidUserId = "xxx";
private List<User> getUsers()
{
return new List<User> {new User {UserId = ValidUserId}};
}
private readonly User newUser= new User();
[SetUp]
public void Setup()
{
repository = A.Fake<IAccountRepository>();
service = new AccountService(repository);
A.CallTo(() => repository.GetById(ValidUserId))
.Returns(new User{UserId = ValidUserId});
A.CallTo(() => repository.GetById(InvalidUserId))
.Returns(null);
A.CallTo(() => repository.Add(A<User>.Ignored))
.???
}
[Test]
public void GetUser_ValidUserId_ReturnsUser()
{
User user = service.GetById(ValidUserId);
Assert.IsNotNull(user);
Assert.AreEqual(ValidUserId, user.UserId);
}
[Test, ExpectedException(typeof(UserNotFoundException))]
public void GetUser_InValidUserId_ThrowsUserNotFoundException()
{
service.GetById(InvalidUserId);
}
[Test]
public void Add_User_AddsUser()
{
service.Add(newUser);
}
}
我可以成功测试 GetUser 方法。但我无法在我的服务类中测试 Add 方法。因为它没有返回任何东西。或者我的服务类没有包含用户来查看状态的列表。你对测试这个 void 方法有什么建议?