Chance Robertson
Chance Robertson

Reputation: 468

FakeItEasy mock error inside method

I have a method I am trying to test and need to test if an error is thrown. If the employee repository throws an error, I want to make sure I get the EmployeeServiceError back. I am using the FakeItEasy mock framework.

Here is the FakeItEasy code:

//  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());

Here is the method I am testing:

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

Upvotes: 0

Views: 553

Answers (2)

Allrameest
Allrameest

Reputation: 4492

This is how I would write it with NUnit:

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

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

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

I renamed the variables since they are not mocks. To prefix them with stub would also work.

Upvotes: 0

Adam Ralph
Adam Ralph

Reputation: 29956

Using xUnit.net, I would do this:

//  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() is an xUnit.net feature. Perhaps NUnit has something similar.

BTW - you should not be catching the general Exception type in your GetEmployees() method, but that is a separate discussion.

Upvotes: 1

Related Questions