2014-03-13 33 views
3

我是新來的最小起訂量,我已閱讀快速入門here。我正在使用MOQ v4.2.1402.2112。我正在嘗試創建一個更新人物對象的單元測試。 UpdatePerson方法返回更新的人員對象。有人能告訴我如何糾正這個問題嗎?最小起訂量錯誤預期的模擬調用一次,但是0次

我收到此錯誤:

Moq.MockException was unhandled by user code 
HResult=-2146233088 
Message=Error updating Person object 
Expected invocation on the mock once, but was 0 times: svc => svc.UpdatePerson(.expected) 
Configured setups: svc => svc.UpdatePerson(It.IsAny<Person>()), Times.Never 
No invocations performed. 
    Source=Moq 
    IsVerificationError=true 

這裏是我的代碼:

[TestMethod] 
    public void UpdatePersonTest() 
    { 
     var expected = new Person() 
     { 
      PersonId = new Guid("some guid value"), 
      FirstName = "dev", 
      LastName = "test update", 
      UserName = "[email protected]", 
      Password = "password", 
      Salt = "6519", 
      Status = (int)StatusTypes.Active 
     }; 

     PersonMock.Setup(svc => svc.UpdatePerson(It.IsAny<Person>())) 
      .Returns(expected) 
      .Verifiable(); 

     var actual = PersonProxy.UpdatePerson(expected); 

     PersonMock.Verify(svc => svc.UpdatePerson(It.IsAny<Person>()), Times.Once(), "Error updating Person object"); 

     Assert.AreEqual(expected, actual, "Not the same."); 
    } 
+0

顯示我們要測試的方法。 –

回答

6

這一行

PersonMock.Verify(svc => svc.UpdatePerson(It.IsAny<Person>()), 
        Times.Once(), // here 
        "Error updating Person object"); 

你是在嘲笑那個UpdatePerson方法應該叫設定期望一旦。它失敗了,因爲你的SUT(類,你正在測試)不會調用此方法都:

No invocations performed

也驗證如果傳遞嘲笑對象PersonProxy。它應該是這樣的:

PersonProxy = new PersonProxy(PersonMock.Object); 

而且實現

public class PersonProxy 
{ 
    private IPersonService service; // assume you are mocking this interface 

    public PersonProxy(IPersonService service) // constructor injection 
    { 
     this.service = service; 
    } 

    public Person UpdatePerson(Person person) 
    { 
     return service.UpdatePerson(person); 
    } 
} 
+0

感謝您的詳細解釋 – haroonxml

相關問題