I have a rather complicated method in a WebAPI MVC project. It does a number of things including hitting a remote server for user authentication. Depending on the results of this, it returns either a redirect (a page), a string error message, or an object representing all of the authentication monkey-business.
It works great when called from a browser. It even works just fine in debug. I can even write a redirect to it and call it "manually", passing in whatever params it needs.
The issue I'm running into is calling it from a test project VS made when I created the WebAPI project. I suspect that it's because because of all the async
and await
that gets thrown about. When it goes into it, eventually it comes back with a "Object not set to instance of an object" error.
Since it works in any other context, I assume that it's because it's inside of a test project and needs to be awaited. Can anyone give me any kind of advice on this?
Edit: to be very specific, it's failing on the second line of code here:
BoxConfig boxConfig = new BoxConfig(ClientID, ClientSecret, enterpriseID, prvt, JWTPublicKeyPass, JWTPublicKeyID);
BoxJWTAuth boxJWT = new BoxJWTAuth(boxConfig); //This is a JSON web token and is needed to authorize the enterprise level app user.
Code context:
This is leveraging the Box.com API. The BoxJWT call creates a JSON Web Token. I don't know where in the process it is failing because when I trace through it, it can't show me the code for things like PEMReader.cs, etc (which have to do with crypto, bouncy castle). But very specifically, the error message detail says the source is Box.V2.JWTAuth.PEMPasswordFinder.GetPassword()
Asynchronous operations may only be started within an asynchronous handler or module or during certain events in the Page lifecycle. If this exception occurred while executing a Page, ensure that the Page is marked <%@ Page Async="true" %> .
Use the Result property on the asynchronous Task, like so: // Synchronous method. void Method()
So, the moral of the story is: you can write async void unit tests in NUnit 2.6. It also works for delegates passed to Assert. Throws , which can have an async modified.
Whenever I create a test method that is going to test async code I make sure the signature of the test method is Async and returns Task. This allows you to avoid the dreaded deadlock that comes from async void. Now you can await inside of the test method.
More info: https://msdn.microsoft.com/en-us/magazine/dn818493.aspx
Example:
[TestMethod]
public async Task myTestMethod()
{
await MyMethodToTest();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With