【问题标题】:How do I write JUnit for my validator class in Java?如何在 Java 中为我的验证器类编写 JUnit?
【发布时间】:2017-05-03 09:54:05
【问题描述】:

我听说 Mockito 框架非常适合用于测试目的。

谁能帮我为下面的代码写一个好的 JUnit。

@Component
public class DataIntegrityValidatorForUpdate extends EmployeeCommonValidator implements Validator {

    @Autowired
    private EmployeeRepository employeeRepository;

    @Override
    public boolean supports(Class<?> paramClass) {
        return Employee.class.equals(paramClass);
    }

    @Override
    public void validate(Object targetObject, Errors errors) {
        if (!(targetObject instanceof Employee))
            return;

        Employee employee = (Employee) targetObject;
        Long employeeId = employee.getId();
        String tenantId = employee.getTenantId();

        // FIXME employee.getId == null or empty then throw error employee id is
        // required
        if (isEmpty(employeeId)) {
            errors.rejectValue("employee.id", "no value", "provide employee id for update");
            return;
        }

        if (!employeeRepository.checkIfEmployeeExists(employeeId, tenantId)) {
            // FIXME throw error employee id does not exist
            errors.rejectValue("employee.id", "no value present", "employee id doesn't exist");
            return;
        }

        validateEmployee(employee, errors);

        validateAssignments(employee.getAssignments(), employeeId, tenantId, errors);

    public void validateEmployee(Employee employee, Errors errors) {
        // FIXME call common validator.validateEmployee
        super.validateEmployee(employee, errors);

        // FIXME : check only for different employees

        if (checkIfColumnValueIsSameInDB("egeis_employee", "code", employee.getCode(), employee.getId(), employee.getTenantId())) {
            errors.rejectValue("employee.code", "invalid", "Employee Code cannot be changed.");
        }

        if ((employee.getPassportNo() != null) && duplicateExists("egeis_employee", "passportNo",   employee.getPassportNo(), employee.getId(), employee.getTenantId())) {
            errors.rejectValue("employee.passportNo", "concurrent", "passportNo already exists");
        }

        if ((employee.getGpfNo() != null) && duplicateExists("egeis_employee", "gpfNo", employee.getGpfNo(), employee.getId(), employee.getTenantId())) {
            errors.rejectValue("employee.gpfNo", "concurrent", "gpfNo already exists");
        }
    }


    private void validateAssignments(List<Assignment> assignments, Long employeeId, String tenantId, Errors errors) {
        validateIdsForAssignment(assignments, employeeId, tenantId, errors);

        for (int index = 0; index < assignments.size(); index++) {
            // validateDocumentsForNewAssignment(assignments.get(index),
            // errors, index);
        }
    }

    private void validateIdsForAssignment(List<Assignment> assignments, Long employeeId, String tenantId, Errors errors) {
        Map<Long, Integer> idsMap = new HashMap<>();
        for (int index = 0; index < assignments.size(); index++) {
            if (assignments.get(index).getId() != null) // FIXME check if long
                                                    // gets default value of
                                                    // 0L
                idsMap.put(assignments.get(index).getId(), index);
        }
        if (!idsMap.isEmpty())
            validateEntityId(idsMap, EntityType.ASSIGNMENT, employeeId, tenantId, errors);
    }


    public Boolean duplicateExists(String table, String column, String value, Long id, String tenantId) {
        Long idFromDb = employeeRepository.getId(table, column, value, tenantId);
        if (idFromDb == 0 || id.equals(idFromDb))
            return false;
        return true;
    }

    public Boolean checkIfColumnValueIsSameInDB(String table, String column, String value, Long id, String tenantId) {
        Long idFromDb = employeeRepository.getId(table, column, value, tenantId);
        if (id.equals(idFromDb))
            return false;
        return true;
    }
}

【问题讨论】:

  • 这太宽泛了——你具体卡在哪里了?
  • 并提示:您要求其他人花时间帮助您。然后你就走开了,没有给出任何反馈。你认为这是礼貌的行为吗?

标签: java junit mockito


【解决方案1】:

鉴于您的生产代码,编写测试非常简单;喜欢:

public class DataIntegrityValidatorForUpdateTest {

@Mock
Errors mockedErrors;
@Mock
EmployeeRepository mockedRepository;

@InjectMocks
DataIntegrityValidatorForUpdate underTest;

@Before
public void setup() {
  initMocks();
}

@Test
public void testNotAnEmployee() {
  underTest.validate("not an employee", mockedErrors);
  verifyZeroInteractions(mockedRepository, mockedErrors);
}

这是做什么的:

  • 它模拟了您需要控制的两个对象以测试此类
  • 它使用@InjectMocks 注释来实例化您要测试的类的实例
  • 然后它会测试您方法的 一个 方面 - 使用参数调用该方法,该参数应导致该方法返回并且什么都不做

以上内容仅供参考。现在您必须对其进行增强,以涵盖您的方法可以采用的所有可能路径。您的大多数测试方法看起来都相似;但是您必须学习如何使用 Mockito 来验证对您的模拟对象的某些调用。

但请不要期望我们会为您这样做。这是您的项目,您必须研究documentation 和tutorials 以了解您需要做什么。

除此之外:从干净代码的角度来看,我建议您重构整个事情。我宁愿抛出 exceptions 来表示验证失败;而不是使用像errors 这样的输入/输出参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-15
    • 2015-03-08
    相关资源
    最近更新 更多