【问题标题】:@Value Integer variable in Spring Controller Causes a jUnit Error (jUnit does not use this variable)Spring Controller中的@Value Integer变量导致jUnit错误(jUnit不使用这个变量)
【发布时间】:2020-04-10 16:48:44
【问题描述】:

我的 jUnit 中有一个 SpringMVC 控制器的奇怪错误,它有一个 @Value Integer 类变量:

@Value("${max.insert.participants.batch.size}")
private Integer maxInsertParticipantsBatchSize;

设置来自属性文件(所有其他设置也可以从中正确读取)

max.insert.participants.batch.size=1000

这是一个属性文件中的变量。它未在 jUnit 中使用或检查,但 jUnit 失败并显示:

12:38:21 Caused by: java.lang.NumberFormatException: For input string: "${max.insert.participants.batch.size}"
12:38:21    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) ~[?:?]

只要我将@Value 类型更改为String 或Boolean,jUnit 就会开始工作。比如

@Value("${max.insert.participants.batch.size}")
private String maxInsertParticipantsBatchSize;

再一次,jUnit 不使用这个变量。仅在实际应用中使用。

【问题讨论】:

  • 测试加载它,但显然没有属性值或属性替换对您的测试无效,因此它将失败(因为它无法转换)。
  • 您能否提供您的测试类代码以获取更多信息?
  • 所以实际上我在属性文件中提供了值。在那里。我还更新了我的 OP 以反映这一点。

标签: spring spring-mvc junit


【解决方案1】:

如果您的测试用例是单元测试,那么这将不起作用。由于单元测试没有初始化弹簧上下文。在单元测试中使用这个变量的值的方法是像这样设置变量值。

ReflectionUtils.setField(fieldName, object, value);

如果您的测试用例是一个组件测试用例,其中 spring 上下文正在初始化,那么您需要像这样在应用程序属性文件中提供值

max.insert.participants.batch.size:3

你也可以像这样提供一个默认值

@Value("${max.insert.participants.batch.size:3}") private Integer maxInsertParticipantsBatchSize;

默认值将被您在应用程序属性文件中提供的值覆盖。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-07
    • 1970-01-01
    • 2023-04-02
    • 2022-01-07
    • 1970-01-01
    • 2017-01-02
    • 2023-03-21
    • 2016-08-27
    相关资源
    最近更新 更多