2015-10-19 73 views
0

我premit我是很新的單元測試,我已經得到了一些麻煩testign此命令測試此命令

internal async Task OnDeleteTreasurerCommandExecute(TesorieraItemResult tesoriera) 
    { 
     try 
     { 
      if (await MessageService.ShowAsync("Confermare l'operazione?", string.Empty, MessageButton.YesNo, MessageImage.Question) == MessageResult.Yes) 
      { 
       await repository.DeleteTesorieraItemAsync(tesoriera.ID_ISTITUTO,tesoriera.ID_DIVISA,tesoriera.PROGRESSIVO); 

       await MessageService.ShowInformationAsync("Operazione completata"); 

       if (SelectedInstitute != null) 
        await OnLoadDataCommandExecute(); 
      } 
     } 
     catch (Exception ex) 
     { 
      ErrorService.HandleError(GetType(), ex); 
     } 
    } 

我使用Catel MVVM作爲框架

我怎麼模擬是/否答案? 謝謝

回答

3

您需要將MessageService替換爲可以返回yes或no answer的類。以下是使用NSubstitute的示例。

  1. Install-Package NSubstitute

  2. Install-Package NUnit

  3. 讓我們說你有一個有 需要有一個方法的類,然後編號:

    public class AccountViewModel 
    { 
        readonly IMessageService _messageService; 
        readonly ICustomerRepository _customerRepository; 
    
        public AccountViewModel(IMessageService messageService, ICustomerRepository customerRepository) 
        { 
         _messageService = messageService; 
         _customerRepository = customerRepository; 
        } 
    
        public async Task OnDeleteCustomer(Customer customer) 
        { 
         if (await MessageService.ShowAsync(
          "Confirm?", 
          string.Empty, 
          MessageButton.YesNo, 
          MessageImage.Question) == MessageResult.Yes) 
         { 
          _customerRepository.Delete(customer); 
          await MessageService.ShowInformationAsync("Completed"); 
         } 
        } 
    } 
    

然後你測試用例如下所示:

public class TestAccountViewModel 
{ 
    [TestCase] 
    public class TestDeleteCustomer() 
    { 
     // arrange 
     var messageService = Substitute.For<IMessageService>(); 
     messageService 
      .ShowAsync(
       Arg.Any<string>(), 
       Arg.Any<string>(), 
       Arg.Any<MessageButton>(), 
       Arg.Any<MessageImage>()) 
      .Returns(Task.FromResult(MessageResult.Yes); 

     messageService 
      .ShowInformationAsync(Arg.Any<string>()) 
      .Returns(Task.FromResult<object>(null)); 

     var customerRepository = Substitute.For<ICustomerRepository>(); 

     // act 
     var sut = new AccountViewModel(messageService, customerRepository); 
     var customer = new Customer(); 
     sut.OnDeleteCustomer(customer); 

     // assert 
     Assert.IsTrue(customerRepository.Received().DeleteCustomer(customer)); 
    } 
} 
0

在過去的版本中,Catel提供了IMessageService的測試實現,它允許您對預期結果進行排隊,以便可以測試命令中的不同路徑。

我剛剛注意到這個類不再可用,但你可以很容易地實現一個測試存根(使用嘲諷等)。或者你可以貢獻給Catel並重新實現測試。

+0

你好吉爾特,因爲我已經寫了你我對單元測試和所有相關的東西(嘲笑,等等)是相當新的,其中的功能是哪個版本?謝謝 – advapi

+0

幾個版本回來,無法回想。 –