Returnsasync(null) throws a build error when using Moq for unit testing in VS15

There are two ReturnsAsync extension methods in Moq ReturnsExtensions class.They have following parameters: (this IReturns<TMock, Task<TResult>> mock, TResult value) (this IReturns<TMock, Task<TResult>> mock, Func<TResult> valueFunction) As you can see one accepts value which should be returned by task, and another accepts delegate which will return value. When you are passing null compiler don’t know whether …

Read more

Moq: Invalid callback. Setup on method with parameters cannot invoke callback with parameters

You need to call the generic overload of Callback with the specific types expected by the method. The following should work: sender.Setup(x => x.SendCommand(It.IsAny<MyCommand>(), false)) .Callback<ICommand, bool>((command, idFromContent) => { var myCommand = command as MyCommand; Assert.That(myCommand, Is.Not.Null); Assert.That(myCommand.Id, Is.EqualTo(cmd.Id)); Assert.That(myCommand.Name, Is.EqualTo(cmd.Name)); }) .Verifiable(); If the assertions fail in the callback then the test fails …

Read more

Verifying event registration using Moq

The moq 4.13 introduced this feature. Now it is possible to verify if add\remove has been invoked. Therefore four new methods have been introduced: SetupAdd SetupRemove VerifyAdd VerifyRemove Example var mock = new Mock<IAdder<EventArgs>>(); mock.SetupAdd(m => m.Added += (sender, args) => { }); mock.Object.Added += (sender, args) => { }; mock.Object.Added += (sender, args) => …

Read more

Using Moq, how do I set up a method call with an input parameter as an object with expected property values?

You can use Verify. Examples: Verify that Add was never called with an UserMetaData with FirstName!= “FirstName1″: storageManager.Verify(e => e.Add(It.Is<UserMetaData>(d => d.FirstName!=”FirstName1”)), Times.Never()); Verify that Add was called at least once with an UserMetaData with FirstName== “FirstName1″: storageManager.Verify(e => e.Add(It.Is<UserMetaData>(d => d.FirstName==”FirstName1”)), Times.AtLeastOnce()); Verify that Add was called exactly once with FirstName == “Firstname1” and …

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