测试这个命令

Testing this command

我对单元测试很陌生,我在测试这个命令时遇到了一些麻烦

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 框架

如何模拟 yes/no 答案? 谢谢

在过去的版本中,Catel 提供了 IMessageService 的测试实现,允许您对预期结果进行排队,以便您可以测试命令内的不同路径。

我刚刚注意到这个 class 不再可用,但您可以轻松地自己实现一个测试存根(使用模拟等)。或者您可以为 Catel 做出贡献并恢复测试实施。

您需要用可以 return 是或否回答的 class 替换 MessageService。这是一个使用 NSubstitute.

的示例
  1. Install-Package NSubstitute

  2. Install-Package NUnit

  3. 假设你有一个 class 有一个方法 需要是,然后否:

    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));
    }
}