[英]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.