我正在尝试使用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);

09-25 22:14