user3257736 user3257736 - 4 months ago 22
Java Question

ReflectionTestUtils.setField (Mockito), not recognizing field.

I am trying to test a Spring Boot Controller by using Mockito. I am following this tutorial: https://www.javacodegeeks.com/2013/07/getting-started-with-springs-mvc-test-framework-part-1.html

The method I am testing is:

public class DigipostSpringConnector {

@Autowired
private String statusQueryToken;

@RequestMapping("/onCompletion")
public String whenSigningComplete(@RequestParam("status_query_token") String token){
this.statusQueryToken = token;
}


So far, I have written this in my test-class:

public class DigipostSpringConnectorTest {

@Before
public void whenSigningCompleteSetsToken() throws Exception{
MockitoAnnotations.initMocks(this);
DigipostSpringConnector instance = new DigipostSpringConnector();
ReflectionTestUtils.setField(instance, "statusQueryToken", statusQueryToken);

}
}


However, I get the error "Cannot resolve symbol statusQueryToken", It seems like the test does not know that I am referring to the private field statusQueryToken, which is in another class.

Any ideas on how to solve this?

Thank you!

Answer

It is because value variable statusQueryToken in whenSigningCompleteSetsToken() method is not defined. Try this:

String statusQueryToken = "statusQueryToken"; 
ReflectionTestUtils.setField(instance, "statusQueryToken", statusQueryToken);
Comments