Björn Ali Göransson February 2016

Making AutoMoq return Fixture-created values for methods

I'd like to explore wether we can save time by setting that all Moq-mocks created by AutoMoq should by default return Fixture-created values as method return values.

This would be beneficial when doing a test like the following:

[TestMethod]
public void Client_Search_SendsRestRequest()
    var client = fixture.Create<Client>();

    // Could be removed by implementing the mentioned functionality
    Mock.Of(JsonGenerator).Setup(j => j.Search(It.IsAny<string>())).Returns(create("JsonBody")));

    client.Search(fixture.Create("query"));

    Mock.Of(client.RestClient).Verify(c => c.Execute(It.IsAny<RestRequest>()));
    Mock.Of(client.RestClient).Verify(c => c.Execute(It.Is<RestRequest>(r => record(r.Body) == record(client.JsonGenerator.Search(query)))));
}

Note that the generated values must be cached inside (?) the proxies, we want the same value "frozen" in order to check. Also, setting up the mock with Setup should override the created value.

So, how can we modify AutoMoq mocks to do this?

A simple test verifying that it works could be:

[TestMethod]
public void MockMethodsShouldReturnCreatedValues()
{
    Guid.Parse(new Fixture().Create<ITest>().Test());
}

public interface ITest
{
    string Test();
}

Answers


dcastro February 2016

Definitely possible, just use the AutoConfiguredMoqCustomization instead of the AutoMoqCustomization. The mocks will use the fixture to generate returns values for all its methods, properties and indexers (*).

Properties will be evaluated eagerly, whereas indexers/methods' return values will be evaluated and cached when invoked for this first time.

(*) There are two exceptions to this rule - the customization cannot automatically setup generic methods or methods with ref parameters, as explained here. You'll have to set those up manually, with the help of the .ReturnsUsingFixture method.

Post Status

Asked in February 2016
Viewed 1,644 times
Voted 10
Answered 1 times

Search




Leave an answer