Search code examples
c#moqreadonly-attribute

How to Setup a readonly property with Moq?


I am trying to unit test using Moq. Here is the example code:

public class ConcreteClass
{
    private readonly FirstPropery firstProperty;
    private readonly SecondProperty secondProperty;

    public ConcreteClass(firstProperty, secondProperty)
    {
        this.firstProperty = firstProperty;
        this.secondProperty = secondProperty;
    }
}

[TestMethod]
    var concreteClassMock = new Mock<ConcreteClass>() { CallBase = true };

In my test method, I want to set firstProperty to reference a real object FirstProperty object (created by a factory), and later use it to test another object's behavior. Is there any way to achieve that?


Solution

  • Usually, you wouldn’t mock private members since you are only mocking the public interface of something. A mock is thus completely independent of implementation details.

    That being said, you can pass constructor arguments to the Mock constructor that will then be passed on to the target’s constructor:

    new Mock<ConcreteClass>(firstProperty, secondProperty) {CallBase = true};
    

    However, if your goal is to actually test the ConcreteClass, you should not create a mock of it. You should test the actual object. So mock its dependencies and pass those if necessary, but keep the object you want to test actually real. Otherwise, you might introduce and test behavior that comes from the mock instead of the object you are testing:

    var firstMock = new Mock<FirstProperty>();
    var secondMock = new Mock<FirstProperty>();
    
    var obj = new ConcreteClass(firstMock.Object, secondMock.Object);
    
    obj.DoSomething();
    // assert stuff