0

I´m using Moq to mock some objects of my application, and for now, I need to mock this call:

accessor.HttpContext.Session.GetInt32("offset");

I have tried to do this way, but not works:

var mock = new Mock<HttpContextAccessor>();
        mock.Setup(x => x.HttpContext.Session.GetInt32("offset"))
            .Returns(0);

It fires this error:

System.NotSupportedException : Expression references a method that does not belong to the mocked object: x => x.HttpContext.Session.GetInt32("offset")

Nkosi
  • 235,767
  • 35
  • 427
  • 472
Beetlejuice
  • 4,292
  • 10
  • 58
  • 84
  • Moq does not work with extension methods. which, based on the error message, can deduce that `GetInt32` is an extension method. Try to avoid mocking types you do not control. Advice: wrap what you are trying to access behind an abstraction you control so that it can be mocked when needed. – Nkosi Mar 31 '17 at 18:46
  • @Nkosi - it's a bit different. The type that is being used by the extension method can be mocked. (Still you can do this directly but you need to setup mock hierarchy) – Pawel Mar 31 '17 at 19:16
  • @Pawel that is correct and would work in this situation because the source for the extension method in question is open source, so we are able to identify what needed to be mocked for the extension method to work. Do note that the same does no hold true for closed source extensions. – Nkosi Mar 31 '17 at 19:24
  • @Nkosi - in general you can't mock static methods and extension methods are just this. The key thing is to be able to mock the dependencies the extension/static method works on - regardless if the project is open source or not. If the dependencies can be mocked everything should be fine. I agree that if the project is not open source figuring out what needs to be mocked and if it can be mocked at all can be challenging. – Pawel Mar 31 '17 at 19:53
  • @Pawel I agree with you. That is what I was pointing out. – Nkosi Mar 31 '17 at 19:55

1 Answers1

2

GetInt32 is an extension method that operates on the ISession interface. You need to mock the ISession interface so that the TryGetValue method returns the expected value (GetInt32 call Get which calls TryGetValue on the ISession interface) and then return the mock from the HttpContext.Session

Pawel
  • 31,342
  • 4
  • 73
  • 104