[英]Use of ReflectionTestUtils.setField() in Junit testing
[英]ReflectionTestUtils.setField (Mockito), not recognizing field.
我試圖通過使用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);
statusQueryToken
未定義,只是因為您尚未定義它。 setField()
的第三個參數定義了要分配給字段的值。 所以,你應該做的事情如下:
ReflectionTestUtils.setField(instance, "statusQueryToken", "the string value to set");
將"the string value to set"
替換"the string value to set"
要分配給字段的任何內容。
然后, ReflectionTestUtils
將在反射的幫助下,在instance
搜索名為statusQueryToken
的字段,並為其指定值"the string value to set"
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.