【发布时间】:2020-02-13 07:18:28
【问题描述】:
您好,我正在使用 MoQ,我想了解为什么我的方法的返回值会被使用。
在下面的示例中,我正在使用模拟接口依赖项创建服务。我正在设置接口方法应返回的内容。
但是,当服务使用我的模拟依赖项时,返回值为 null ,而不是我在 Returns 方法中设置的那个。
为什么会这样?
型号
public class SomeModel
{
public string Name {get;set;}
}
模拟依赖
public interface IDependency
{
Task<SomeModel> GetByIdAsync(string input);
}
使用模拟依赖的服务
public class SomeService
{
private IDependency dependency;
public SomeService(IDependency dependency)
{
this.dependency=dependency;
}
public async Task<SomeModel> GetByIdAsync(string id)
{
var model=await this.dependency.GetByIdAsync(id); //why is the result null , i have set the `Returns`
if(model==null)
{
throw new NotSupportedException();
}
return model;
}
}
测试类
public class MyTest
{
[Testcase("data")]
public async Task CanGetById(string value)
{
var model=new SomeModel{Name=value};
var dependency=new Mock<IDependency>();
dependency.Setup(x=>x.GetByIdAsync(value)).Returns(Task.FromResult(model)).Verifiable(); //i have set up the return of the dependency
var service=new SomeService(dependency.Object);
var clone=await service.GetByIdAsync(value);
dependency.Verify();
}
}
【问题讨论】:
-
这里的
data是什么var model=await this.dependency.GetByIdAsync(data);?应该是id? -
对不起,我忘了这是一个错字。
-
@BercoviciAdrian 基于显示的测试和被测主题,只要设置中使用的值是调用主题时实际传递的值,这应该可以工作
标签: c# unit-testing .net-core moq