Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 917
M.Tach Avatar asked Aug 15 '16 08:08

M.Tach


1 Answers

A few remarks:

1- It could be easily achieve with an interface and a get method like this:

public interface IConcreteClass
{
    FirstProperty FirstProperty { get; }
}

    [Test]
    public void TestCase()
    {
        var yourFirstPropertyImplementation = new FirstProperty();
        var concreteClassMock = new Mock<IConcreteClass>();
        concreteClassMock.Setup(o => o.FirstProperty).Returns(yourFirstPropertyImplementation);
    }

2- Depending of your scenario, do you really need a Moq, why not just use the true implementation and use moq only at boundaries?

3- You should clarify what you want to test? If it's concrete class? or the properties? or some other classes? The test case I propose in 1 is valid only to test the interaction of concrete class with some other classes.

like image 138
Ouarzy Avatar answered Sep 20 '22 13:09

Ouarzy