我试图测试我的控制器,该控制器有一个RequestParam配置了一个指向占位符的默认值的处理程序:
@Controller
public class AgeController {
@GetMapping("/age")
public String home(@RequestParam(name="current", defaultValue="${default.age}") Integer age) {
return "age"+age;
}
}
当我通过浏览器进行测试时,这种方法很正常,但是当我使用以下测试用例时,它会引发异常:
测试用例:
public class AgeControllerTest {
AgeController controller
MockMvc mockMvc;
@Before
public void setUp() {
ageController = new AgeController();
mockMvc = MockMvcBuilders.standaloneSetup(controller).addPlaceholderValue("default.age", "10").build();
}
@Test
public void test() {
mockMvc.perform(get("/age")).andExpect(status().isOk());
}
}
例外:
Caused by: java.lang.NumberFormatException: For input string: "${default.age}"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.valueOf(Unknown Source)
at org.springframework.util.NumberUtils.parseNumber(NumberUtils.java:208)
at org.springframework.beans.propertyeditors.CustomNumberEditor.setAsText(CustomNumberEditor.java:113)
at org.springframework.beans.TypeConverterDelegate.doConvertTextValue(TypeConverterDelegate.java:468)
at org.springframework.beans.TypeConverterDelegate.doConvertValue(TypeConverterDelegate.java:441)
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:199)
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:108)
at org.springframework.beans.TypeConverterSupport.doConvert(TypeConverterSupport.java:64)
at org.springframework.beans.TypeConverterSupport.convertIfNecessary(TypeConverterSupport.java:47)
at org.springframework.validation.DataBinder.convertIfNecessary(DataBinder.java:713)
at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:120)
答案 0 :(得分:0)
考虑使用@TestPropertySource。
@TestPropertySource(properties = {"default.age = 10"})
public class AgeControllerTest {
...
}