Tag Archives: testing

Development

Mocking users in ASP.NET MVC 5

So historically unit testing has been a constant non-starter for me. It seems every time I start to write unit tests (whether it’s in an attempt to do some TDD, or just trying produce unit tests for an existing piece of code), I struggle to get over the hump of dependencies that I’ve incidentally placed in my way without even thinking.

Things as simple as getting the current user’s ID using User.Identity.GetUserId() seem harmless, until you realise that in your test the User object will be null.

When dealing with dependencies in the code that you are testing, a common method is to replace these dependencies with a mock. For example, say you have a service which calls off to an external API to get some data; in your test code, you could mock (aka “fake”) that service to just return some fake data rather than calling to the external API.

Read More