我正在測試我創建的存儲庫模式,並使用Moq包來模擬我的對象。我想測試2個對象的引用,但結果令我驚訝。下面是測試:Assert.AreSame的這種情況應該返回true嗎?
Mock<Repository<Web_Documents>> moqRepo;
Mock<Repository<Web_Documents>> moqRepo2;
public void ObjEqGetTest()
{
//context is DBContext and has been initialized using [TestInitialize] annotation
moqRepo = new Mock<Repository<Web_Documents>>(context);
moqRepo2 = new Mock<Repository<Web_Documents>>(context);
var test = moqRepo.Object.Get(1L);
var test2 = moqRepo2.Object.Get(1L);
Assert.AreSame(test, test2);
}
我的get方法返回:
return entities.SingleOrDefault(predicate)
使用Expression
建設者正在創建predicate
(如果需要,我可以添加代碼)。
當我創建了兩個不同的對象時,爲什麼這個Assert
返回true?
每次從數據庫中獲取數據(因爲它指向正在使用的模型),Get方法是否返回相同的引用?
感謝您的幫助!
編輯 @CodeCaster表示Mocking回購將在我提出的請求中返回null。但是,當我在我的表Web_Documents中驗證值時,Assertions返回true。讓我來證明這一點:
public void IdExistsGetTest()
{
moqDoc = new Mock<Repository<Web_Documents>>(context);
var testDoc = moqDoc.Object.Get(1L);
Assert.AreEqual(testDoc.NomDocument, "Ajouter une catégorie");
}
這個測試是成功的,在Web_Documents,在ID = 1
該行已NomDocument = "Ajouter une catégorie"
。
請閱讀[問]並創建[mcve]。你也不應該依賴DbContext進行單元測試,嘲笑這一點。嘲笑被測試的課程是毫無意義的,你嘲笑依賴關係。 test和test2都是null,這是平等的。 – CodeCaster
我以錯誤的前提爲基礎回答了我的問題,並將其刪除。我所聲稱的只是嘲笑一個界面,而不是嘲笑一個具體的類。我沒有想到Moq在其方法尚未建立的時候會進入具體的課程。儘管如此,你仍然在使用完全錯誤的模擬,會嘗試編輯答案。 – CodeCaster
@CodeCaster我對你說的有什麼問題。我的'Repository'需要一個DBContext參數,所以如果我只嘲笑上下文,當我創建它時如何給我的'Repository'提供一個DBContext參數? –