2013-12-17 96 views
0

我正在通過本教程http://blogs.telerik.com/justteam/posts/13-10-25/30-days-of-tdd-day-17-specifying-order-of-execution-in-mocks關於TDD。我正試圖將一個JustMock聲明改編成Moq。以下設置不匹配 - 將JustMock轉換爲Moq

enter code here [Test] 
    public void testname() 
    { 
     var customerId = Guid.NewGuid(); 
     var customerToReturn = new Customer { Id = customerId}; 

     //JustCode 
     Mock _customerService = Mock.Create<ICustomerService>(); 
     Mock.Arrange(() => _customerService.GetCustomer(customerId)).Returns(customer).OccursOnce(); 


     //Moq 
     Mock<ICustomerService> _customerService = new Mock <ICustomerService>(); 
     _customerService.Setup(os => os.GetCustomer(customerId)).Returns(customerToReturn); 
     _customerService.VerifyAll(); 
    } 

當測試跑了,我得到這個異常:

Moq.MockVerificationException : The following setups were not matched:ICustomerService os => os.GetCustomer(a1a0d25c-e14a-4c68-ade9-bc3d7dd5c2bc) 

當我改變.VerifyAll()來.Verify(),測試通過,但我不確定這是否正確。

問題:什麼是適應此代碼的正確方法? .VerifyAll()與.OccursOnce()不相似嗎?

+0

下面的答案有幫助嗎? – Spock

+0

是的,謝謝你的兩個例子。 – derguy

回答

1

看來你缺少設置上的.verifiable。你也可以避免任何可驗證的,只需在最後使用mock.Verify。您還必須調用模擬實例,以便進行可驗證的工作。 https://github.com/Moq/moq4/wiki/Quickstart

請參閱下面2種方法。

[Test] 
    public void testname() 
    { 
     var customerId = Guid.NewGuid(); 
     var customerToReturn = new Customer { Id = customerId}; 

     //Moq 
     var _customerService = new Mock <ICustomerService>(); 
     _customerService.Setup(os => os.GetCustomer(customerId)).Returns(customerToReturn).Verifiable(); 

     var cust = _customerService.Object.GetCustomer(customerId); 

     _customerService.VerifyAll(); 
    } 


    [Test] 
    public void testname1() 
    { 
     var customerId = Guid.NewGuid(); 
     var customerToReturn = new Customer { Id = customerId }; 

     //Moq 
     var _customerService = new Mock<ICustomerService>(); 
     _customerService.Setup(os => os.GetCustomer(customerId)).Returns(customerToReturn); 

     var cust = _customerService.Object.GetCustomer(customerId); 

     _customerService.Verify(x => x.GetCustomer(customerId)); 
    } 
+0

我有點困惑。在第二個測試中,進行設置並驗證是否使用重複的調用代碼'GetCustomer(customerId)'? – 2015-11-02 02:25:22