[英]Mocking an interface which is { get; } only (Moq)
我有一个IUnitOfWork
接口,它包含所有存储库的映射,如下所示:
public interface IUnitOfWork : IDisposable
{
IRepository<Client> ClientsRepo { get; }
IRepository<ConfigValue> ConfigValuesRepo { get; }
IRepository<TestRun> TestRunsRepo { get; }
//Etc...
}
我们的IRepository
类看起来像这样:
public interface IRepository<T>
{
T getByID(int id);
void Add(T Item);
void Delete(T Item);
void Attach(T Item);
void Update(T Item);
int Count();
}
我的问题是我正在尝试测试一个使用IUnitOfWork
getById()
方法,但是这个方法是通过IUnitOfWork
对象访问的,如下所示:
public static TestRun getTestRunByID(IUnitOfWork database, int testRun)
{
TestRun testRun = database.TestRunsRepo.getByID(testRun);
return testRun;
}
在我的测试中,我嘲笑了两件事; IUnitOfWork
和IRepository
。 我已经配置了IRepository
以便它返回一个TestRun
项,但是我实际上无法使用这个repo,因为在getTestRunByID()
方法中它从IUnitOfWork
对象获得它自己的repo。 结果,这会导致NullReferenceException
。
我已经尝试将我的repo添加到IUnitOfWork的repo但是它不会编译,因为所有repos都被标记为{get; } 只要。 我的测试是:
[TestMethod]
public void GetTestRunById_ValidId_TestRunReturned()
{
var mockTestRunRepo = new Mock<IRepository<TestRun>>();
var testDb = new Mock<IUnitOfWork>().Object;
TestRun testRun = new TestRun();
mockTestRunRepo.Setup(mock => mock.getByID(It.IsAny<int>())).Returns(testRun);
//testDb.TestRunsRepo = mockTestRunRepo; CAN'T BE ASSIGNED AS IT'S READ ONLY
TestRun returnedRun = EntityHelper.getTestRunByID(testDb, 1);
}
如何让我的IUnitOfWork's
repo不抛出NullReferenceException
?
您无法分配给模拟,您需要通过安装程序配置属性。
testDb.Setup(m => m.TestRunsRepo).Returns(mockTestRunRepo.Object);
尝试:
testDb.SetupGet(m => m.TestRunsRepo).Returns(mockTestRunRepo.Object);
要么
testDb.SetupGet(m => m.TestRunsRepo).Returns(mockTestRunRepo.Object);
我想在你的安排中你会想要这样的东西:
testDb.Setup(n => n.TestRunsRepo).Returns(mockTestRunRepo.Object);
当你更容易设置模拟并让它以你想要的方式返回时,你正试图为mocks对象分配一些东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.