![](/img/trans.png)
[英]How to call explicit interface implementation methods internally without explicit casting?
[英]How to unit test explicit interface implemented methods?
我在服务中使用以下方法,但是在单元测试中无法调用它。 该方法使用async/ await
代码,但是(我认为是导致我出现问题的原因)也使用点符号表示该方法的名称,我不确定这到底是什么吗? 请参阅下面的示例
实作
async Task<IEnumerable<ISomething>> IMyService.MyMethodToTest(string bla)
{
...
}
单元测试
[Fact]
public void Test_My_Method()
{
var service = new MyService(...);
var result = await service.MyMethodToTest(""); // This is not available ?
}
更新资料
尝试过建议,但无法与以下错误消息一起编译
await operator can only be used with an async method.
是的, 显式接口实现只能在接口类型的表达式上调用,而不能在实现类型上调用。
只需先将服务转换为接口类型,或使用其他变量即可:
[Fact]
public async Task Test_My_Method()
{
IMyService serviceInterface = service;
var result = await serviceInterface.MyMethodToTest("");
}
要么
[Fact]
public async Task Test_My_Method()
{
var result = await ((IMyService) service).MyMethodToTest("");
}
我个人更喜欢前一种方法。
注意将返回类型从void
更改为Task
,并使方法async
。 这与显式接口实现无关,仅与编写异步测试有关。
尝试这个
var result = await ((IMyService)service).MyMethodToTest("");
要么
[Fact]
public async void Test_My_Method()
{
IMyService service = new MyService(...);
var result = await service.MyMethodToTest("");
}
您至少应使用xUnit.net 1.9才能使用async
。 如果您使用的是较低版本,则应使用以下版本:
[Fact]
public void Test_My_Method()
{
IMyService service = new MyService(...);
var result = await service.MyMethodToTest("");
Task task = service.MyMethodToTest("")
.ContinueWith(innerTask =>
{
var result = innerTask.Result;
// ... assertions here ...
});
task.Wait();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.