我正在尝试使用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,它位于另一个类中。
关于如何解决这个问题的任何想法?
谢谢!
答案 0 :(得分:6)
这是因为未定义whenSigningCompleteSetsToken()方法中的值变量statusQueryToken。试试这个:
String statusQueryToken = "statusQueryToken";
ReflectionTestUtils.setField(instance, "statusQueryToken", statusQueryToken);
答案 1 :(得分:1)
statusQueryToken
未定义,只是因为您尚未定义它。 setField()
的第三个参数定义了要分配给字段的值。所以,你应该这样做:
ReflectionTestUtils.setField(instance, "statusQueryToken", "the string value to set");
将"the string value to set"
替换为您要分配给该字段的任何内容。
ReflectionTestUtils
会在instance
中搜索名为statusQueryToken
的字段,并为其指定值"the string value to set"
。