如何设置IRepository <t>

时间:2016-07-21 19:57:21

标签: c# unit-testing nunit moq

我正试图像这样设置:

[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);

    }
}

但是当调用GetAllObservations()函数时,它会在实际代码中返回null。

在实际代码中,IRepository是依赖注入的,它工作正常。

正在返回的对象看起来像这样。

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

正在测试的实际功能如下所示

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;
    }

依赖注入看起来像这样

    private IRepository<WspObservation> _wspObsrep;

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

1 个答案:

答案 0 :(得分:0)

的目的是什么?
var sut = mock.Create<CommonServices>();

创建真正的SUT对象并注入IRepository模型是不是更好?

我会这样做:

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

var sut = new CommonServices(repoMock);