簡體   English   中英

反射 - 在 controller spring 中設置私有字段

[英]Reflection - Set Private field in controller spring

我使用 Spring MVC。

我的 controller 中有一個私有字段。 該字段的值來自屬性文件,因為,

@Controller
public Class MainController() {

   @Value("${my-value}")
   private int myValue;

}

我必須覆蓋 selenium 測試中的值。 如何覆蓋此字段的值,意味着我要設置自定義值(以便不從屬性文件中獲取值)?

能不能這樣,

ReflectionTestUtils.setField(MainController.class, "myValue", 3, Integer.class);

您應該在 controller 測試方法中使用這些代碼。

 @WebMvcTest(controllers = MainController.class, useDefaultFilters = false) @Import({MainController.class}) public void MainControllerTest{ @Autowired private MainController mainController; @Test should_set_controller_private_field(){ ReflectionTestUtils.setField(mainController, "myValue", 3); assertEquals(ReflectionTestUtils.getField(mainController, "myValue"), 3); } }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM