[英]Mock and Inject inherited fields
我在繼承和編寫單元測試方面遇到了問題。 我不知道如何將mock作為一個字段注入,當我想要測試的類繼承這個字段時。 請注意,我不能存根任何東西,因為測試類是一個額外的測試包。 我只是想讓myService.getSomething()
call工作。
public class A{
@Autowired
private Service myService;
protected void doSomething(){
//
someValue = myService.getSomething();
}
而B類繼承了這些方法:
public class B extends A{
public void someMethod(){
doSomething();
}
}
這將是我的Testclass:
public class TestB{
@Mock
private Service myService;
@InjectMocks
private B classUnderTest = new B();
@Before
public void setUp(){
MockitoAnnotations.initMocks(this);
}
@Test
public void testSomeMethod(){
SomeValue someValue = new SomeValue();
doReturn(someValue).when(myService).getSomething();
classUnderTest.doSomething();
}
}
謝謝你的幫助。
一種可能的方法是使用java反射來設置/更改運行時中的字段:
Field parentService = classUnderTest.getClass().getSuperclass().getDeclaredField("myService");
parentService.setAccessible(true);
parentService.set(classUnderTest, myService_mock);
正在尋找解決方案,這對我有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.