Search code examples
c#nunitnsubstitute

How to mock read only property of interface in interface is already mocked


public interface IPerson
{
    SalaryCalculator SalaryCalculator { get; }
}

public interface ISalaryCalculator
{

}

public class SalaryCalculator : ISalaryCalculator
{
    public int  JoiningDate { get; set; }
    public SalaryCalculator(int joiningDate)
    {
        JoiningDate = joiningDate;
    }
}

[TestFixture]
public class PersonFixture
{
    IPerson person;
    [SetUp]
    public void SetUp()
    {
        person = Substitute.For<IPerson>();
    }

    [Test]
    public void TestPerson()
    {
        person.SalaryCalculator.Returns(new SalaryCalculator());
          OR
        person.SalaryCalculator.Returns(Substitute.For<ISalaryCalculator>());
    }
}

I tried to mock using above two options but does not works,

NSubstitute.Exceptions.CouldNotSetReturnDueToTypeMismatchException : Can not return value of type ISalaryCalculatorProxy for IPerson.get_SalaryCalculator (expected type SalaryCalculator).

How can we mock in this case?


Solution

  • The exception indicates what the mocked member should be returning.

    ...expected type SalaryCalculator

    return the actual class since that is what the mocked interface member returns.

    SalaryCalculator instance = new SalaryCalculator(1);
    
    person.SalaryCalculator.Returns(instance);