gpt4 book ai didi

java - Spring ReflectionTestUtils 不设置原始数据类型字段

转载 作者:行者123 更新时间:2023-12-01 19:56:52 26 4
gpt4 key购买 nike

我使用 ReflectionTestUtils 在我的服务类中设置 int 字段来测试该类。我的服务类别如下:

@Service
public class SampleService {

@Value("${app.count}")
private int count;

@Value("${app.countStr}")
private String countStr;

public int getCount() {
return count;
}

public void setCount(int count) {
this.count = count;
}

public String getCountStr() {
return countStr;
}

public void setCountStr(String countStr) {
this.countStr = countStr;
}

@PostConstruct
public int demoMethod() {
return count + Integer.parseInt(countStr);
}
}

测试类如下:

@RunWith(SpringRunner.class)
public class SampleServiceTest {

@Autowired
private SampleService sampleService;

@TestConfiguration
static class SampleServiceTestConfig {

@Bean
public SampleService sampleService() {
return new SampleService();
}
}

@Before
public void init() {
ReflectionTestUtils.setField(sampleService, "count", new Integer(100));
ReflectionTestUtils.setField(sampleService, "countStr", 100);
}

@Test
public void testDemoMethod() {
int a = sampleService.demoMethod();
Assert.assertTrue(a == 200);
}
}

当我运行此测试用例时,它给出以下错误:

Caused by: java.lang.NumberFormatException: For input string: "${app.count}"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:569)
at java.lang.Integer.valueOf(Integer.java:766)
at org.springframework.util.NumberUtils.parseNumber(NumberUtils.java:210)
at org.springframework.beans.propertyeditors.CustomNumberEditor.setAsText(CustomNumberEditor.java:115)
at org.springframework.beans.TypeConverterDelegate.doConvertTextValue(TypeConverterDelegate.java:466)
at org.springframework.beans.TypeConverterDelegate.doConvertValue(TypeConverterDelegate.java:439)
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:192)
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:117)
at org.springframework.beans.TypeConverterSupport.doConvert(TypeConverterSupport.java:70)
... 47 more

为什么 ReflectionTestUtils 尝试在字段中设置字符串值?

我放置了 2 个字段,一个是整数,另一个是字符串用于测试目的。

您可以找到源代码here .

请查看并提出解决方法。

最佳答案

测试时,您必须提供属性源。如果您不添加属性,它会将值注入(inject)变量的 @Value 内。在您的情况下,它尝试将字符串添加到给出 NumberFormatException 的整数中。尝试添加如下:

@RunWith(SpringRunner.class)
@TestPropertySource(properties = {"app.count=1", "app.countStr=sampleString"})
public class SampleServiceTest{...}

当您使用@Autowired时,在ReflectionTestUtils之前它会尝试在@Value中添加值。

关于java - Spring ReflectionTestUtils 不设置原始数据类型字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49335226/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com