【问题标题】:How to unit test explicit interface implemented methods?如何对显式接口实现的方法进行单元测试?
【发布时间】:2016-10-23 06:35:22
【问题描述】:

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

【问题讨论】:

  • IMyService.MyMethodToTest 暗示 MyMethodToTest 是接口 IMyService 的方法 MyMethodToTest 的实现

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


【解决方案1】:

是的,显式接口实现只能在 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方法。这与显式接口实现无关,只是写异步测试。

【讨论】:

  • 感谢您的帮助,虽然它仍然无法正常工作,但我已经用错误消息更新了我的问题
  • @Jamie:嗯,是的,但这是一个完全不同的问题。您需要使您的测试方法异步。会更新我的答案,但基本上你应该一次研究一个问题。
【解决方案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();
}

【讨论】:

    猜你喜欢
    • 2011-03-08
    • 1970-01-01
    • 2020-02-05
    • 1970-01-01
    • 2015-11-03
    • 2015-03-24
    • 2018-01-11
    • 2021-07-29
    • 1970-01-01
    相关资源
    最近更新 更多