Moq: unit testing a method relying on HttpContext

Webforms is notoriously untestable for this exact reason – a lot of code can rely on static classes in the asp.net pipeline. In order to test this with Moq, you need to refactor your GetSecurityContextUserName() method to use dependency injection with an HttpContextBase object. HttpContextWrapper resides in System.Web.Abstractions, which ships with .Net 3.5. It is … Read more

Using Moq to Mock a Func constructor parameter and Verify it was called twice

I don’t think it is necessary to use a mock for the Func. You can simply create an ordinary Func yourself that returns a mock of IFooBarProxy: int numberOfCalls = 0; Func<IFooBarProxy> func = () => { ++numberOfCalls; return new Mock<IFooBarProxy>(); }; var sut = new FooBar(func); sut.Process(); Assert.Equal(2, numberOfCalls);

Use ItExpr.IsNull rather than a null argument value, as it prevents proper method lookup

When setting up an IProtectedMock, you should use Moq.Protected.ItExpr instead of Moq.It. Here is the corrected implementation of what I was trying to do in my question: _innerHandler.Protected() .Setup<Task<HttpResponseMessage>>(“SendAsync”, ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>()) .ReturnsAsync(responseMessage);

Expression references a method that does not belong to the mocked object

This problem occurs because you are trying to mock Select method, which is an extension method, not an instance method of IEnumerable<T>. Basically, there is no way to mock an extension method. Have a look at this question for some ideas that you may find useful. UPD (12/11/2014): To gain more understanding on mocking extension … Read more

How do you mock the session object collection using Moq

I started with Scott Hanselman’s MVCMockHelper, added a small class and made the modifications shown below to allow the controller to use Session normally and the unit test to verify the values that were set by the controller. /// <summary> /// A Class to allow simulation of SessionObject /// </summary> public class MockHttpSession : HttpSessionStateBase … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)