我正在為 spring boot 應用程式中的一個組件撰寫一個 junit 測驗用例。該組件具有@Value 注釋并從屬性檔案中讀取值。
當我運行我的 Junit 5 (mockito) 并且控制元件轉到組件時;該值為空。
我曾嘗試:我曾經
@ExtendWith(SpringRunner)和改變@injectMocks來@Autowired和@mock到@MockBeans,但是這不是我想要的(正如其成為集成測驗。)
Junit類:
@ExtendWith(MockitoExtension.class)
public class ItemMessageProcessorTest {
private static final String VALUE1 = "Value 1";
private static final String VALUE2 = "Value 2";
private static final String VALUE3 = "Value 3";
@InjectMocks
private MyComponent component;
組件類:
@Slf4j
@Component
public class MyComponent {
@Value("${my-val.second-val.final-val}")
private String myValue;
這個 myValue 在同一個組件類中被使用:
public void myMethod(){
myObject.setMyValue(Integer.parseInt(myValue));
}
我正在尋找的是這樣的:如果我有機會模擬 parseInt,或者從測驗類本身加載值。任何線索都會有很大幫助。 注意:我無法更改組件類中的任何內容。
uj5u.com熱心網友回復:
在這種情況下,我會進行建構式注入:
@Slf4j
@Component
public class MyComponent {
private final String myValue;
MyComponent(@Value("${my-val.second-val.final-val}" String myValue)) {
this.myValue = myValue;
}
}
uj5u.com熱心網友回復:
您可以使用 Spring 反射 utills 方法使用 @Value 設定欄位值進行單元測驗:
org.springframework.test.util.ReflectionTestUtils.setField(classUnderTest, "field", "value");
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/331723.html
