Mocking Static Methods

@Pure.Krome: good response but I will add a few details @Kevin: You have to choose a solution depending on the changes that you can bring to the code. If you can change it, some dependency injection make the code more testable. If you can’t, you need a good isolation. With free mocking framework (Moq, RhinoMocks, … Read more

Mocking Asp.net-mvc Controller Context

Using MoQ it looks something like this: var request = new Mock<HttpRequestBase>(); request.Expect(r => r.HttpMethod).Returns(“GET”); var mockHttpContext = new Mock<HttpContextBase>(); mockHttpContext.Expect(c => c.Request).Returns(request.Object); var controllerContext = new ControllerContext(mockHttpContext.Object , new RouteData(), new Mock<ControllerBase>().Object); I think the Rhino Mocks syntax is similar.

How to mock the Request on Controller in ASP.Net MVC?

Using Moq: var request = new Mock<HttpRequestBase>(); // Not working – IsAjaxRequest() is static extension method and cannot be mocked // request.Setup(x => x.IsAjaxRequest()).Returns(true /* or false */); // use this request.SetupGet(x => x.Headers).Returns( new System.Net.WebHeaderCollection { {“X-Requested-With”, “XMLHttpRequest”} }); var context = new Mock<HttpContextBase>(); context.SetupGet(x => x.Request).Returns(request.Object); var controller = new YourController(); controller.ControllerContext = … Read more

Mocking HttpClient in unit tests

HttpClient’s extensibility lies in the HttpMessageHandler passed to the constructor. Its intent is to allow platform specific implementations, but you can also mock it. There’s no need to create a decorator wrapper for HttpClient. If you’d prefer a DSL to using Moq, I have a library up on GitHub/Nuget that makes things a little easier: … Read more

Assigning out/ref parameters in Moq

For ‘out’, the following seems to work for me. public interface IService { void DoSomething(out string a); } [TestMethod] public void Test() { var service = new Mock<IService>(); var expectedValue = “value”; service.Setup(s => s.DoSomething(out expectedValue)); string actualValue; service.Object.DoSomething(out actualValue); Assert.AreEqual(expectedValue, actualValue); } I’m guessing that Moq looks at the value of ‘expectedValue’ when you … Read more

tech