我有以下問題,同時以起訂量框架單元測試C#代碼:驗證,如果方法調用起訂量
我無法檢查(TestCaseExecutions.Add())被執行了多少次給定的方法。執行計數器始終爲零。
在「問題是在這裏」的評論有兩條線標記爲「1」和「2」。
「1」 是負責迭代TestCaseExecutions.Add(TestCaseExecution)呼叫計數器。
「2」是需要在方法SomeMethodThatUsesMockedContext(mockContext.Object)在這個表上的操作,沒有任何LINQ查詢將拋出空指針異常。
註釋出 「2」 線和SomeMethodThatUsesMockedContext方法和添加
mockContext.Object.TestCaseExecutions.Add(new TestCaseExecution());
只是前驗證方法導致與通過之後。
如何解決這個問題,爲什麼用行「2」莫名其妙中和線「1」?
[Test()]
public void SomeTest()
{
//Internal counters.
int saveChanges = 0;
int AddedExecutions = 0;
//Mock DatabaseContext
var mockContext = new Mock<TestRunsEntities>();
mockContext.Setup(x => x.SaveChanges()).Callback(() => saveChanges++);
...
//Mock of one of it's tables
var mockTestCaseExecution = new Mock<DbSet<TestCaseExecution>>();
//PROBLEM IS HERE (I think)
mockContext.Setup(x => x.TestCaseExecutions.Add(It.IsAny<TestCaseExecution>())).Callback(() => addExecution++); //1
mockContext.Setup(c => c.TestCaseExecutions).Returns(mockTestCaseExecution.Object); //2
//Inside this method Save(), and TestCaseExecutions.Add(TestCaseExecution ex) are called.
//I have checked in debug mode that they are called once for my test scenario.
SomeMethodThatUsesMockedContext(mockContext.Object);
//After execution, saveChanges is equal to 1 as expected but AddedExecutions is equal to 0
//This step fails.
mockContext.Verify(x => x.TestCaseExecutions.Add(It.IsAny<TestCaseExecution>()), Times.Once());
...
}
隨溶液編輯:
問題在於線標記爲「1」,並在調用的驗證。
我對這些行使用了不正確的上下文。
前:
mockContext.Setup(x => x.TestCaseExecutions.Add(It.IsAny<TestCaseExecution>())).Callback(() => addExecution++); //1
後:
mockTestCaseExecution.Setup(x => x.Add(It.IsAny<TestCaseExecution>())).Callback(() => addExecution++);
也是一樣的驗證方法,在最後一行。
是'TestCaseExecutions.Add'方法虛擬? – galenus 2014-11-24 15:03:28
@galenus,我認爲這是[這一個](http://msdn.microsoft.com/en-us/library/system.data.entity.dbset.add(V = vs.113)的.aspx),因此,是的,它是虛擬的 – takemyoxygen 2014-11-24 15:06:21
是的,它是從實體框架上下文生成的方法。 – 2014-11-24 15:13:50