2015-04-06 31 views
0

如果我有,我想檢查方法,出於某種原因,我想測試用例在2個獨立的情況下,拆分,我會喜歡這樣做:Nsubstitute Returns在其他測試用例中未被覆蓋?

[Test] 
    public void EditCustomerShouldReturnExceptionWhenCustomerIsNotCreated() 
    { 
     var c = new CustomerViewModel(); 
     _customerRepositoryMock.Update(Arg.Any<Customer>()).Returns(x => { throw new Exception(); }); 
     Assert.Throws<Exception>(() => _customerService.EditCustomer(c)); 
    } 

    [Test] 
    public void EditCustomerShouldReturnTrueWhenCustomerIsCreated() 
    { 
     var c = new CustomerViewModel(); 
     _customerRepositoryMock.Update(Arg.Any<Customer>()).Returns(true); 
     Assert.IsTrue(_customerService.EditCustomer(c)); 
    } 

但這裏的問題是,當第一測試用例被傳遞.Update返回值是一個異常,所以當第二個測試用例想獲得返回值時,它也會得到新的Exception();作爲回報價值?爲什麼會發生?我如何覆蓋同一方法的返回值?

回答

1

發生這種情況是因爲您的_customerRepositoryMock是您的測試類中的一個字段,您正在使用您的SetUp方法進行初始化。我不確定爲什麼在每次測試通過後都保留了設置值,因爲SetUp方法應該在每種測試方法之前運行。你是否也實施了TearDown

一般來說,我強烈建議你使用局部變量而不是字段。特別是在測試中,甚至當你以不同的方式爲每種測試方法設置你的模擬時更是如此。

如果您使用局部變量,則不會得到此行爲。

編輯:試試這個:

[Test] 
public void EditCustomerShouldReturnExceptionWhenCustomerIsNotCreated() 
{ 
    var c = new CustomerViewModel(); 
    var customerRepositoryMock = Substitute.For<ICustomerRepository>(); 
    var customerService = new CustomerService(customerRepositoryMock); 
    customerRepositoryMock.Update(Arg.Any<Customer>()).Returns(x => { throw new Exception(); }); 
    Assert.Throws<Exception>(() => customerService.EditCustomer(c)); 
} 

[Test] 
public void EditCustomerShouldReturnTrueWhenCustomerIsCreated() 
{ 
    var c = new CustomerViewModel(); 
    var customerRepositoryMock = Substitute.For<ICustomerRepository>(); 
    var customerService = new CustomerService(customerRepositoryMock); 
    customerRepositoryMock.Update(Arg.Any<Customer>()).Returns(true); 
    Assert.IsTrue(customerService.EditCustomer(c)); 
} 

或者,看着a similar question,你可能只需要改變你的第二個方法的返回值,爲lambda:

_customerRepositoryMock.Update(Arg.Any<Customer>()).Returns(x => true); 

哪個我想,你更喜歡什麼。

+0

thx很多,定義局部變量解決了我的問題 – Timsen 2015-04-06 13:41:27