-
Notifications
You must be signed in to change notification settings - Fork 267
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Mock throwing an exception for async methods #609
Comments
Hi @A-l-e-x-e-y , Thanks for raising this issue. I think this answer is correct: we need to use For why this is necessary, consider these two implementations of public interface IExample {
Task<string> AsyncMethod(bool fail);
}
public class Example : IExample {
public async Task<string> AsyncMethod(bool fail) {
if (fail) throw new NotImplementedException();
// do async stuff
return "hi";
}
}
public class OtherExample : IExample {
public Task<string> AsyncMethod(bool fail) {
if (fail) throw new NotImplementedException();
return Task.Run(() => {
// do async stuff
return "hi";
});
}
} Both throwing synchronously and throwing asynchronously both meet the required contracts, so we have to support both. To make this easier, how would you feel about adding It could mirror the existing
|
Hi @dtchepak , Thank you for detailed explanation. I understand the problem. And I agree that it would be more convenient and easier to use something like |
@A-l-e-x-e-y Would you have time to send a PR through with this change? |
|
Hello, I'm also interested by Are you accepting PR for this ? |
Hi @Socolin , yes I'd definitely be happy to accept a PR for this! :) |
The problem is described here in comments under the answer: https://stackoverflow.com/questions/38338906/nsubstitute-mock-throwing-an-exception-in-method-returning-task
The problem with this is that the exception is thrown at the wrong time.
var t = AsyncMethod(); (actual behavior: exception will be raised here)
await t; (expected behavior: exception will be raised here)
With an async method the exception should be thrown when awaiting the task, Current approach throws the exception immediately.
Current behavior little bit unexpected in some cases. It would be great to correct it. Or may there is more elegant way to solve the problem.
The text was updated successfully, but these errors were encountered: