简体   繁体   中英

How to moq setup IRepository<T>

I am trying to setup like this:

[Test]
public void Observatoins_Were_Returned()
{
    using (var mock = AutoMock.GetLoose())
    {
        // Arrange
        mock.Mock<IRepository<WspObservation>>()
            .Setup(x => x.GetAll())
            .Returns(_observations);

        var sut = mock.Create<CommonServices>();                              
        WspResponse wspResponse;

        // Act
        var wspObservations = sut.GetAllObservations(out wspResponse);
        var expectedErrorCode = ResponseCodes.SUCCESS;

        // Assert
        // Assert.AreEqual(expectedErrorCode, wspResponse.ResponseCode);

    }
}

but when GetAllObservations() function is called it returns null in the actual code.

In the actual code IRepository is dependency injected which is working fine.

object that is being returned looks like this.

      var _observations = new List<WspObservation>();
        _observations.Add(new WspObservation() { DeviceName = "Devcie One", Steps = "3000"  });
        _observations.Add(new WspObservation() { DeviceName = "Devcie One", Steps = "2000" });

the actual function that is being tested looks like this

public List<WspObservation> GetAllObservations(out WspResponse getAllWspObservationsResponse)
    {
        List<WspObservation> allWspObservations = new List<WspObservation>();
        getAllWspObservationsResponse = new WspResponse();
        try
        {
            //some other Business Logic
            allWspObservations = _wspObsrep.GetAll().ToList();
            //some other Business Logic
        }
        catch (Exception ex)
        {
            getAllWspObservationsResponse.ResponseCode = ResponseCodes.DatabaseGetError;

        }
        return allWspObservations;
    }

dependency injection looks like this

    private IRepository<WspObservation> _wspObsrep;

    public CommonServices(IRepository<WspObservation> wspObsrep)
    {
        _wspObsrep = wspObsrep;
    }

What is the intention of

var sut = mock.Create<CommonServices>();

Isn't it better to Create the real SUT object and inject the IRepository mock?

I would do it this way:

var repoMock = mock.Mock<IRepository<WspObservation>>()
        .Setup(x => x.GetAll())
        .Returns(_observations);

var sut = new CommonServices(repoMock);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM