无法屈服

时间:2018-08-27 19:20:28

标签: .net unit-testing mocking nsubstitute

[Theory]
[InlineData("12345678901","bob")]
[InlineData("12345678902", "alice")]
public void Customer_Registration_Should_Succeed(string identityId, string name)
{
    Customer customer = new Customer(identityId, name);

    _customerRepository.Add(customer).Returns(customer);

    var customerService = new CustomerService(_customerRepository);

    var expectedCustomer = customerService.Register(identityId, name);

    Assert.Equal(expectedCustomer, customer);

}

我有上面的测试代码。

这是服务:

public class CustomerService : ICustomerService
{
    readonly ICustomerRepository _customerRepository;
    public CustomerService(ICustomerRepository customerRepository)
    {
        _customerRepository = customerRepository;
    }

    public Customer Register(IdentityId identityId, Name name)
    {
        var customer = new Customer(identityId, name);
        var newCustomer = _customerRepository.Add(customer);

        return newCustomer;
    }
}

以下是存储库:

public class CustomerRepository : ICustomerRepository
{
    IList<Customer> _customers;

    public CustomerRepository()
    {
        _customers = new List<Customer>();
    }

    public Customer Add(Customer customer)
    {
        _customers.Add(customer);

        return customer;
    }
}

但是我得到了空引用异常。

Assert.Equal(expectedCustomer, customer);

并且断言失败。为什么?

1 个答案:

答案 0 :(得分:2)

正在创建两个单独的实例,

被测方法。

public Customer Register(IdentityId identityId, Name name)
{
    var customer = new Customer(identityId, name); //<-- HERE
    var newCustomer = _customerRepository.Add(customer);

    return newCustomer;
}

和测试

//...

Customer customer = new Customer(identityId, name); // <--HERE

_customerRepository.Add(customer).Returns(customer);

//...

问题是测试中的实例用作配置替代项的参数。

替换项将从设置中获取确切的实例,但是被测试的方法正在传递自己的实例,这将导致替换项由于参数不匹配而返回null。

一种选择是设置替代项,以返回传递给调用成员的参数。

例如

_customerRepository.Add(Arg.Any<Customer>()).Returns(_ => _.Arg<Customer>());

可以根据需要断言

[Theory]
[InlineData("12345678901","bob")]
[InlineData("12345678902", "alice")]
public void Customer_Registration_Should_Succeed(string identityId, string name) {
    //Arrange
    _customerRepository.Add(Arg.Any<Customer>()).Returns(_ => _.Arg<Customer>());
    var customerService = new CustomerService(_customerRepository);

    //Act
    var actual = customerService.Register(identityId, name);

    //Assert
    Assert.IsNotNull(actual);
    Assert.AreEqual(actual.IdentityId, identityId);
    Assert.AreEqual(actual.Name, name);

    //Check received with the arg:
    _customerRepository.Received().Add(actual);
}