【发布时间】:2016-01-14 12:01:13
【问题描述】:
我有一个 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();
}
我的问题是我正在尝试测试一个使用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,但它不会编译,因为所有 repo 都标记为 { 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 存储库不抛出NullReferenceException?
【问题讨论】:
标签: c# unit-testing moq