Mocking generic methods in Moq without specifying T

In Moq 4.13 they introduced the It.IsAnyType type which you can using to mock generic methods. E.g. public interface IFoo { bool M1<T>(); bool M2<T>(T arg); } var mock = new Mock<IFoo>(); // matches any type argument: mock.Setup(m => m.M1<It.IsAnyType>()).Returns(true); // matches only type arguments that are subtypes of / implement T: mock.Setup(m => m.M1<It.IsSubtype<T>>()).Returns(true); … Read more

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

How to test method call order with Moq

I recently created Moq.Sequences which provides the ability to check ordering in Moq. You may want to read my post that describes the following: Supports method invocations, property setters and getters. Allows you to specify the number of times a specific call should be expected. Provides loops which allow you to group calls into a … Read more

What is the purpose of Verifiable() in Moq?

ADDENDUM: As the other answer states, the purpose of .Verifiable is to enlist a Setup into a set of “deferred Verify(…) calls” which can then be triggered via mock.Verify(). The OP’s clarification makes it clear that this was the goal and the only problem was figuring out why it wasn’t working, but as @Liam prodded, … Read more

Mocking EF DbContext with Moq

I managed to solve it by creating a FakeDbSet<T> class that implements IDbSet<T> public class FakeDbSet<T> : IDbSet<T> where T : class { ObservableCollection<T> _data; IQueryable _query; public FakeDbSet() { _data = new ObservableCollection<T>(); _query = _data.AsQueryable(); } public virtual T Find(params object[] keyValues) { throw new NotImplementedException(“Derive from FakeDbSet<T> and override Find”); } public … Read more