如何单元测试显式接口实现的方法?

时间:2016-06-21 15:48:54

标签: c# .net interface xunit explicit-implementation

我在服务中有以下方法,但我未能在单元测试中调用它。该方法使用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.

2 个答案:

答案 0 :(得分:4)

是的,显式接口实现只能在 interface 类型的表达式上调用,而不能在实现类型上调用。

首先将服务转换为接口类型,或使用其他变量:

[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。这与显式接口实现无关,而只是编写异步测试。

答案 1 :(得分:2)

试试这个

var result = await ((IMyService)service).MyMethodToTest("");  

reasons

有很多implementing an interface explicitly

或者

[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();
}
相关问题