方法内的FakeItEasy模拟错误

时间:2013-02-20 17:09:51

标签: mocking fakeiteasy

我有一个我试图测试的方法,需要测试是否抛出错误。如果员工存储库抛出错误,我想确保我得到EmployeeServiceError。我正在使用FakeItEasy模拟框架。

这是FakeItEasy代码:

//  Arrange
        var service = new EmployeeService(mockEmployeeRepository, mockCryptographer, mockApplicationUserRepository, mockEmployeeAddressRepository);

        IEnumerable<EmployeeDTO> employeeDTOs;

        //  Act
        employeeDTOs = service.GetEmployees();

        //  Assert
// How do I check the EmployeeServiceException thrown?

        A.CallTo(() => mockEmployeeRepository.GetAllForUi())
            .Throws(new NullReferenceException());

以下是我正在测试的方法:

public IEnumerable<EmployeeDTO> GetEmployees()
        {
            IEnumerable<EmployeeDTO> employeeDTOs = null;

            try
            {
                var employees = _employeeRepository.GetAllForUi();
                employeeDTOs = Mapper.Map(employees, employeeDTOs);
            }
            catch (Exception exception)
            {
                throw new EmployeeServiceException(exception);
            }

            return employeeDTOs;
        }

2 个答案:

答案 0 :(得分:1)

使用xUnit.net,我会这样做:

//  Arrange
A.CallTo(() => mockEmployeeRepository.GetAllForUi())
    .Throws(new NullReferenceException());

var service = new EmployeeService(
    mockEmployeeRepository,
    mockCryptographer,
    mockApplicationUserRepository,
    mockEmployeeAddressRepository);

//  Act
var exception = Record.Exception(() => service.GetEmployees();

//  Assert
Assert.IsType<EmployeeServiceException>(exception);

Record.Exception()是xUnit.net功能。也许NUnit有类似的东西。

BTW - 您不应该在Exception方法中捕获常规GetEmployees()类型,但这是一个单独的讨论。

答案 1 :(得分:0)

这是我用NUnit写的方式:

A.CallTo(() => fakeEmployeeRepository.GetAllForUi())
    .Throws(new NullReferenceException());

var service = new EmployeeService(fakeEmployeeRepository, fakeCryptographer, fakeApplicationUserRepository, fakeEmployeeAddressRepository);

Assert.Throws<EmployeeServiceException>(() => service.GetEmployees());

我重命名了变量,因为它们不是模拟。用stub作为前缀也可以。