我正在使用xUnit为需要查询数据库以验证记录已存在的方法创建单元测试。在测试中,我使用NSubstitute来Mock
我的存储库。
因此:
public class MyTestClass
{
public MyTestClass()
{
myRepository = Substitute.For<IMyRepository>();
}
[Fact]
public void My_Test()
{
var myService = new MyService(myRepository);
var result = myService.Create(mockObject);
....
}
这是我引用的服务的实现:
public class MyService
{
public MyService(IMyRepository repository)
{
_repository = repository
}
IMyRepository _repository;
public X Create(MyObject mockObject)
{
var result = _repository.CheckIfExists(mockObject.Name); //This return an NAME for example;
if (result == mockObject.Name)
{
return X.Error("Message...")
}
}
}
问题是:
由于我的存储库为FAKE,如何测试服务的if (result == mockObject.Name)
?我需要在测试班级上收到此消息return X.Error("Message...")
。
如何测试此代码段?
答案 0 :(得分:1)
需要对模拟/替代进行配置,使其行为符合测试的预期
例如
public class MyTestClass {
public MyTestClass()
myRepository = Substitute.For<IMyRepository>();
}
[Fact]
public void My_Test() {
//Arrange
myRepository.CheckIfExists(mockObject.Name).Returns(mockObject.Name);
var myService = new MyService(myRepository);
//Act
var result = myService.Create(mockObject);
//Assert
//....check that the returned result is as expected.
}
}