![](/img/trans.png)
[英]Use of ReflectionTestUtils.setField() in Junit testing
[英]ReflectionTestUtils.setField (Mockito), not recognizing field.
我试图通过使用Mockito测试Spring Boot Controller。 我正在关注本教程: https : //www.javacodegeeks.com/2013/07/getting-started-with-springs-mvc-test-framework-part-1.html
我正在测试的方法是:
public class DigipostSpringConnector {
@Autowired
private String statusQueryToken;
@RequestMapping("/onCompletion")
public String whenSigningComplete(@RequestParam("status_query_token") String token){
this.statusQueryToken = token;
}
到目前为止,我已经在我的测试类中写了这个:
public class DigipostSpringConnectorTest {
@Before
public void whenSigningCompleteSetsToken() throws Exception{
MockitoAnnotations.initMocks(this);
DigipostSpringConnector instance = new DigipostSpringConnector();
ReflectionTestUtils.setField(instance, "statusQueryToken", statusQueryToken);
}
}
但是,我收到错误“无法解析符号statusQueryToken”,似乎测试不知道我指的是私有字段statusQueryToken,它在另一个类中。
关于如何解决这个问题的任何想法?
谢谢!
这是因为未定义whenSigningCompleteSetsToken()方法中的值变量statusQueryToken。 尝试这个:
String statusQueryToken = "statusQueryToken";
ReflectionTestUtils.setField(instance, "statusQueryToken", statusQueryToken);
statusQueryToken
未定义,只是因为您尚未定义它。 setField()
的第三个参数定义了要分配给字段的值。 所以,你应该做的事情如下:
ReflectionTestUtils.setField(instance, "statusQueryToken", "the string value to set");
将"the string value to set"
替换"the string value to set"
要分配给字段的任何内容。
然后, ReflectionTestUtils
将在反射的帮助下,在instance
搜索名为statusQueryToken
的字段,并为其指定值"the string value to set"
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.