测试一个做某事的方法以及抛出异常

时间:2014-01-24 08:56:29

标签: nunit moq

我开始使用TDD(和MoQ)。我有一个方法接受订单并为该订单创建唯一的CustomerId。

public class CustomerService
    {

        public CustomerService(IOrderRepository orderRepo)
        {
            _orderRepo = orderRepo;
        }

        public string Create(Order order)
        {
            //1. Save the Order that comes in, irrespective of being valid or not.
            _orderRepo.Save(order);

            //2. If the order is invalid, throw an exception.
            if (!isValid(order))
                throw new ArgumentException();

            //3. Create a Customer, generate a unique CustomerId and return that.
            return createCustomerAndGenerateCustomerId(order);
        }

    }

以下测试似乎无法正常运行:

    [Test]
    [ExpectedException(typeof(ArgumentException))]
    public void Create_WhenPassedInvalidOrder_StillPersistsIt()
    {
        //Arrange
        var order = new Order(); //This is invalid, as it has some mandatory fields missing
        var mockOrderRepo = new Mock<IOrderRepository>();
        var customerService = new CustomerService(mockOrderRepo.Object);

        //Act
        customerService.Create(order);  //This should call Save() on the order repo, but still throw an exception.

        //Assert
        mockOrderRepo.Verify(o => o.Save(order), Times.Once());
    }

即使我不调用_orderRepo.Save(),此测试也始终通过。我做错了什么?

1 个答案:

答案 0 :(得分:1)

您无法在此方案中使用ExpectedException,因为Nunit会在测试级别尝试/捕获异常,因此您的mockOrderRepo.Verify永远不会被调用。

因此,您手动需要尝试捕获customerService.Create调用 - 如果您想要在抛出的异常上手动断言 - 或者您Assert.Throws if you're using Nunit 2.5 or higher

[Test]
public void Create_WhenPassedInvalidOrder_StillPersistsIt()
{
    //Arrange
    var order = new Order(); 
    var mockOrderRepo = new Mock<IOrderRepository>();
    var customerService = new CustomerService(mockOrderRepo.Object);

    //Act
    Assert.Throws<ArgumentException>(() => customerService.Create(order));

    //Assert
    mockOrderRepo.Verify(o => o.Save(order), Times.Once());
}