简体   繁体   English

如何moq设置IRepository <T>

[英]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. 但是,当调用GetAllObservations()函数时,它将在实际代码中返回null。

In the actual code IRepository is dependency injected which is working fine. 在实际代码中,IRepository是依赖项注入,可以正常工作。

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? 创建真正的SUT对象并注入IRepository模拟不是更好吗?

I would do it this way: 我会这样:

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

var sut = new CommonServices(repoMock);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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