2015-10-19 75 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

几个版本回来,无法回想。 –