如何设置IRepository<;T>;
本文关键字:lt gt IRepository 何设置 设置 | 更新日期: 2023-09-27 17:58:03
我正在尝试这样设置:
[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;
}
的意图是什么
var sut = mock.Create<CommonServices>();
创建真正的SUT对象并注入IRepository mock不是更好吗?
我会这样做:
var repoMock = mock.Mock<IRepository<WspObservation>>()
.Setup(x => x.GetAll())
.Returns(_observations);
var sut = new CommonServices(repoMock);