Reputation: 321
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.
Upvotes: 0
Views: 999
Reputation: 20764
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();
}
Upvotes: 2
Reputation: 1502006
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.
Upvotes: 4