【问题标题】:JUnit: test if ID of type int is null when creating JavaBeanJUnit:创建JavaBean时测试int类型的ID是否为null
【发布时间】:2016-09-09 09:16:53
【问题描述】:

我对测试有点陌生。我有一个带有 spring boot 和 oracle db 的小应用程序。当我的 JavaBean 类可以有空的 ID int 值时,我想编写一个测试。这甚至可以测试吗?

目前我有这段代码,但我认为它不正确。

ReportModel reportModel = new ReportModel();

Validator validator = createValidator();
Set<ConstraintViolation<ReportModel>> constraintViolationSet = validator.validate(reportModel);

assertThat(constraintViolationSet.size()).isEqualTo(0);

已编辑:完整的测试类:

public class ValidatorTests {

    private Validator createValidator() {
        LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean();
        localValidatorFactoryBean.afterPropertiesSet();
        return localValidatorFactoryBean;
    }

    @Test
    public void shouldNotValidateWhenIdIsNull() {
        LocaleContextHolder.setLocale(Locale.ENGLISH);
        ReportModel reportModel = new ReportModel();

        Validator validator = createValidator();
        Set<ConstraintViolation<ReportModel>> constraintViolationSet = validator.validate(reportModel);

        assertThat(constraintViolationSet.size()).isEqualTo(0);
    }
}

【问题讨论】:

  • 您能否提供更多背景信息?还有更多的测试代码?测试与上下文文件和运行器的正确路径连接的 bean。并添加更多细节现在不起作用?检查 bean 是否有空 id 是否有问题?或者你甚至不能运行测试?
  • 什么不工作:测试失败。下面的答案解决了这个问题。
  • 很好,然后将其标记为正确答案。

标签: java junit spring-boot


【解决方案1】:

试试这个:

assertEquals(constraintViolationSet.size(), 0);

或者,

assertTrue(constraintViolationSet.isEmpty());

【讨论】:

  • 如果这解决了任何问题,那么你的问题就出在其他地方,因为这个“解决方案”只是用一个基本相同的 Hamcrest 断言替换了你的 AssertJ 断言。您可以使用 AssertJ 编写与 assertThat(constraintViolationSet).isEmpty() 相同的内容 - 而不会冒 NullPointer 的风险。但这并不能解释你原来的问题出在哪里。
  • 我最初的问题是我的测试没有通过。现在它们通过了,但我不确定测试实体 bean 的参数是否为空是否正确。但这已经是另一个问题了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-27
  • 2016-10-31
  • 1970-01-01
  • 1970-01-01
  • 2013-08-26
相关资源
最近更新 更多