简体   繁体   中英

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!

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

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

statusQueryToken is undefined, simply because you haven't defined it. The third parameter to setField() defines which value you want to assign to the field. So, you should do something like:

ReflectionTestUtils.setField(instance, "statusQueryToken", "the string value to set");

Replace "the string value to set" with whatever you want to assign to the field.

ReflectionTestUtils will then, with the help of reflection , search in instance for a field called statusQueryToken , and assign the value "the string value to set" to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM