Ashley Kilgour
Ashley Kilgour

Reputation: 1258

MOQ setting properties on a object

I am having to work with a class that has unknown dependencys and probably other code smell.

I can not make changes this class and its used in loads of other projects I dont want to touch.

I have created a factory that creates this object and sets the properties.

I want unit tests for this factory, and since this object unknown dependency's I am creating a mock using MOQ.

I have the problem, that I can not set properties on a MOQ object. I want it set by the factory NOT by using

    mock.Setup(x => x.FirstName).Returns(firstName);

So here is my demo code and the tests

    [TestCase("John")]
    [TestCase("Paul")]
    [TestCase("George")]
    [TestCase("Ringo")]
    public void Create(string firstName)
    {
        //arrange
        var mock = new Mock<IPerson>();

        //act
        var actual = PersonFactory.Create(mock.Object, firstName);
        //assert
        Assert.AreEqual(firstName, actual.FirstName);
    }

The factory looks like this

public static class PersonFactory
{
    public static IPerson Create(IPerson person, string firstName)
    {
        person.FirstName = firstName;
        return person;
    }
}

I have tried this with NSubsitute and got it working okay. I suspect its need a .object somewhere.

Upvotes: 2

Views: 1538

Answers (1)

Nkosi
Nkosi

Reputation: 247571

Allow the mock to record the values assigned to properties by callin

mock.SetupAllProperties(); //Stub all properties on a mock (not available on Silverlight):

Reference MOQ Quickstart: Properties

[TestCase("John")]
[TestCase("Paul")]
[TestCase("George")]
[TestCase("Ringo")]
public void Create(string firstName) {
    //arrange
    var mock = new Mock<IPerson>();
    mock.SetupAllProperties();

    //act
    var actual = PersonFactory.Create(mock.Object, firstName);

    //assert
    Assert.AreEqual(firstName, actual.FirstName);
}

You could also verify the property set directly

mock.VerifySet(foo => foo.FirstName = firstName);

For example

[TestCase("John")]
[TestCase("Paul")]
[TestCase("George")]
[TestCase("Ringo")]
public void Create(string firstName) {
    //arrange
    var mock = new Mock<IPerson>();

    //act
    var actual = PersonFactory.Create(mock.Object, firstName);

    //assert
    mock.VerifySet(_ => _.FirstName = firstName);   
}

Upvotes: 1

Related Questions