I am trying to mock the OWIN context in a C# WEB API REST service but the OWIN context always seems to be null. I am using moq and .NET framework 4.5.2.
Here is the cont
First off, I see where you've setup your mock of IOwinContext
, but none of the code that you've shown has actually tied your mock into the request. Specifically, there's nothing setup that causes controller.Request.GetOwinContext()
to return your mocked object. So, since you haven't setup an expectation for that call, it will return null.
The real pain that you're running into is from trying to Mock someone else's very wide interfaces (plural). That's always a painful thing to do. As evidence, look at the amount of code you've had to write to initialize and execute your test. I would try and hide the access to these things behind interfaces that are much more focused and easy to mock / stub / dummy.
As much of a unit testing zealot as I am, I don't ever test my WebAPI or MVC controllers in isolation. They almost always depend on external things that I don't want to dummy up like HttpContext
, authentication concerns, method-level attributes. Instead, I keep the controllers as thin as possible, mostly limiting the methods to marshalling things in and out of the context, etc. All of the business logic gets moved into classes that the controllers depend on. Then, those classes are easier to test because they don't depend on things that are a pain to fake.
I still write tests that exercise the controller methods, and generally they cover every branch of the controllers. It's just that these are system-level functional tests like automated browser tests for MVC apps or tests that hit the API using an HttpClient
for WebAPI apps. If the controllers are kept thin, then there isn't much there to get test coverage on in the first place.