Unable to mock Owin context in C# WEB API REST service unit test

孤街浪徒 提交于 2019-12-01 21:43:26

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.

Testing

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!