在单元测试中模拟Java枚举?

7d7tgy0s  于 2023-02-11  发布在  Java
关注(0)|答案(1)|浏览(131)

我有以下工厂类

public class EmployeeFactory {

    public static Employee createEmployee(Employee employee) {

        switch (employee) {
            case DOCTOR:
                return new Doctor();
            case NURSE:
                return new Nurse();
        }

       throw new EmployeeException("Invalid Employee!");
    }

}
    • 枚举类:**
public enum Employee {

    DOCTOR("Doctor"),
    NURSE("Nurse");

    private final String description;

    Employee(String description) {
        this.description = description;
    }

    public String getDescription() {
        return description;
    }
}

我想创建一个模拟枚举,例如TEACHER,它是我的factory方法的无效输入,以Assertexception被抛出。
我怎么能这样做呢?

    • 当前测试:**
@Test
    void shouldThrowException(){

        assertThrows(EmployeeException.class,
                () -> {
                    // arrange
                    //todo - how to?
                    Employee invalidEmployee = mock(Employee.class);
                    when(invalidEmployee.getDescription()).thenReturn("Teacher");

                    // act
                    EmployeeFactory.createEmployee(invalidEmployee);
                });
    }
kgsdhlau

kgsdhlau1#

你可以使用mockStatic,像这样嘲笑新员工:

try (MockedStatic<Employee> employeeEnumMock = mockStatic(Employee.class)) {
        Employee TEACHER = mock(Employee.class);
        when(TEACHER.ordinal()).thenReturn(2);

        employeeEnumMock.when(Employee::values).thenReturn(new Employee[]{Employee.DOCTOR, Employee.NURSE, TEACHER});
        // call createEmployee with your teacher enum
        EmployeeFactory.createEmployee(TEACHER);
    }

相关问题