0

In my controller I have a line of code like this

string method = HttpContext.Request.HttpMethod;

and based on if it is a GET or POST, method is doing different things that I want test. But first I should be able to mock this. We are using NSubstitute.

I did some research and the closest I found was this answer but none of them are using NSubstitue.

Mocking Asp.net-mvc Controller Context

Any help is appreciated.

Community
  • 1
  • 1
Bohn
  • 26,091
  • 61
  • 167
  • 254

1 Answers1

1

Creating mocks and configuring return values is described in the NSubstitute documentation.

So we can create a mock IFoo using:

var foo = Substitute.For<IFoo>();

We can configure a member to return a specific value using Returns:

// Make HttpMethod property return "GET"
foo.HttpMethod.Returns("GET");

// Make someOtherMock.GetFoo() return foo 
someOtherMock.GetFoo().Returns(foo);

And we can inject a mocked value into another class:

var x = new Context(foo, ... );

I think that's everything required to port the linked code examples1. If you need any more info please comment and I'll update the answer.


1 I'm avoiding posting the full translation as it probably varies for different MVC versions. Hopefully this answer will help you port any snippet you need.
Community
  • 1
  • 1
David Tchepak
  • 9,826
  • 2
  • 56
  • 68