当方法返回null时如何在J-Unit中测试?

时间:2018-03-27 13:39:35

标签: java jpa junit mockito converter

它们是我的方法,我正在测试它们:当我不将null作为参数时,它很好,但是当我将参数设为null时,我无法测试?我无法理解它的逻辑。

这就是我的转换器方法:

 @Override
    public Integer convertToDatabaseColumn(WorkerId id) {
        if (Assert.isNull(id)) {
            return null;
        }
        return id.getValue();
    }

    @Override
    public WorkerId convertToEntityAttribute(Integer s) {
        if (Assert.isNull(s)) {
            return null;
        }
        return new WorkerId(s);
    }

那就是我的测试方法:

@Test
public void testConvertToDatabaseColumn() {
    WorkerId workerId = new WorkerId(1);
    Integer result = workerIdConverter.convertToDatabaseColumn(workerId);
    assertThat(result).isEqualTo(workerId.getValue());
}

@Test
public void testIfIdNull() {
    WorkerId workerId = null;
    Integer result = workerIdConverter.convertToDatabaseColumn(workerId);
    assertThat(result).isEqualTo(workerIdConverter.convertToDatabaseColumn(null));
}

1 个答案:

答案 0 :(得分:1)

您不需要也不应该调用两次测试方法 这就够了:

@Test
public void testIfIdNull() {
    WorkerId workerId = null;
    Integer result = workerIdConverter.convertToDatabaseColumn(workerId);
    assertThat(result).isEqualTo(null);
}

或者更简单地没有匹配器(这在这里没有帮助):

@Test
public void testIfIdNull() {
    WorkerId workerId = null;
    Integer result = workerIdConverter.convertToDatabaseColumn(workerId);
    Assert.assertNull(result);
}

由于断言和测试方法简洁,你甚至可以在一行中写下所有内容而不降低可读性:

@Test
public void testIfIdNull() {
    Assert.assertNull(workerIdConverter.convertToDatabaseColumn(null));
}