2

I have a class I am unit testing and all I want to do is to verify that the public setter gets called on the property. Any ideas on how to do this?

I don't want to check that a value was set to prove that it was called. I only want to ensure that the constructor is using the public setter . Note that this property data type is a primitive string

user2309367
  • 317
  • 2
  • 8

1 Answers1

0

This is not the sort of scenario that mocking is designed for because you are trying to test an implementation detail. Now if this property was on a different class that the original class accessed via an interface, you would mock that interface and set an expectation with the IgnoreArguments syntax:

public interface IMyInterface
{
    string MyString { get; set; }
}

public class MyClass
{
    public MyClass(IMyInterface argument)
    {
        argument.MyString = "foo";
    }
}

[TestClass]
public class Tests
{
    [TestMethod]
    public void Test()
    {
        var mock = MockRepository.GenerateMock<IMyInterface>();
        mock.Expect(m => m.MyString = "anything").IgnoreArguments();
        new MyClass(mock);
        mock.VerifyAllExpectations();
    }
}

There are 2 problems with what you are trying to do. The first is that you are trying to mock a concrete class, so you can only set expectations if the properties are virtual.

The second problem is the fact that the event that you want to test occurs in the constructor, and therefore occurs when you create the mock, and so occurs before you can set any expectations.

If the class is not sealed, and the property is virtual, you can test this without mocks by creating your own derived class to test with such as this:

public class RealClass
{
    public virtual string RealString { get; set; }

    public RealClass()
    {
        RealString = "blah";
    }
}

[TestClass]
public class Tests
{
    private class MockClass : RealClass
    {
        public bool WasStringSet;

        public override string RealString
        {
            set { WasStringSet = true; }
        }
    }

    [TestMethod]
    public void Test()
    {
        MockClass mockClass = new MockClass();
        Assert.IsTrue(mockClass.WasStringSet);
    }
}
lockstock
  • 2,359
  • 3
  • 23
  • 39