Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReflectionTestUtils.setField (Mockito), not recognizing field.

Tags:

java

spring

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!

like image 873
Nora Avatar asked Apr 27 '26 09:04

Nora


1 Answers

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

String statusQueryToken = "statusQueryToken"; 
ReflectionTestUtils.setField(instance, "statusQueryToken", statusQueryToken);
like image 183
Jeet Avatar answered Apr 29 '26 04:04

Jeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!