0

I have the following method in a service but I'm failing to call it in my unit test. The method uses the async/ await code but also (and which I think is causing me the problem) has the name of the method with a dot notation which I'm not sure what that does to be honest? See my example below

Implementation

async Task<IEnumerable<ISomething>> IMyService.MyMethodToTest(string bla)
{
    ...
}

Unit test

[Fact]
public void Test_My_Method()
{
   var service = new MyService(...);
   var result = await service.MyMethodToTest("");  // This is not available ?
}

Update

Have tried the suggestions but it does not compile with the following error message

await operator can only be used with an async method.
Jamie
  • 321
  • 1
  • 6
  • 18
  • IMyService.MyMethodToTest implies that MyMethodToTest is an implementation for the method MyMethodToTest of the interface IMyService – Camilo Terevinto Jun 21 '16 at 15:50

2 Answers2

4

Yes, explicit interface implementations can only be invoked on an expression of the interface type, not the implementing type.

Just cast the service to the interface type first, or use a different variable:

[Fact]
public async Task Test_My_Method()
{
    IMyService serviceInterface = service;
    var result = await serviceInterface.MyMethodToTest("");
}

Or

[Fact]
public async Task Test_My_Method()
{
    var result = await ((IMyService) service).MyMethodToTest("");
}

Personally I prefer the former approach.

Note the change of return type from void to Task, and making the method async. This has nothing to do with explicit interface implementation, and is just about writing async tests.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • thank you for your help although it still doesn't work, I've updated my question with the error message – Jamie Jun 22 '16 at 10:03
  • 1
    @Jamie: Well yes, that's an entirely different problem though. You need to make your test method async. Will update my answer, but basically you should research one problem at a time. – Jon Skeet Jun 22 '16 at 10:04
2

Try this

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

There are many reasons for implementing an interface explicitly

Or

[Fact]
public async void Test_My_Method()
{
   IMyService service = new MyService(...);
   var result = await service.MyMethodToTest("");  
}

You should use at least xUnit.net 1.9 to be able to use async. If you are using a lower version then you should use this:

[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();
}
Community
  • 1
  • 1
Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74