我發現有關與的Mockito嘲諷的任何實例的工作原理類似於此接口(這些只是codesnipets):模擬更深層次的類/使用的Mockito
考慮:
public interface MyInterface {
public String doWhatever();
}
public class MyClass {
@Autowired
MyInterface myInterface;
public String doSomething() {
return myInterface.doWhatever();
}
}
嘲諷:
@Mock
MyInterface myInterfaceMock;
@InjectMocks
MyClass myClass;
@Test
public void test() throws Exception {
when(myInterfaceMock.doWhatever()).thenReturn("foo");
String result = myClass.doSomething();
...
}
然而,當引入第二類時,使用更深的級別:
public class MyOtherClass {
@Autowired
MyInterface myInterface;
public MyInterface getMyInterface() {
return myInterface;
}
}
更深層次的嘲諷類結構進行時,總是這樣的:
public class MyClass {
MyOtherClass myOtherClass = new MyOtherClass();
public MyOtherClass getOtherClass() {
return myOtherClass;
}
}
@Test
public void test() throws Exception {
given(myClass.getOtherClass().getMyInterface().doSomething()).willReturn("bar");
String result = myClass.getOtherClass().getMyInterface().doSomething();
}
中查看information
然而,這並不能反映類結構我應該測試此深存根例子。給定結構如下:
public interface MyInterface {
public String doWhatever();
}
public class MyOtherClass {
@Autowired
MyInterface myInterface;
public String doOtherThing() {
return myInterface.doWhatever();
}
}
public class MyClass {
MyOtherClass myOtherClass = new MyOtherClass();
public String doSomething() {
return myOtherClass().doOtherThing();
}
}
現在,我想嘲弄它與此類似:
@Mock
MyInterface myInterfaceMock;
@InjectMocks
MyClass myClass;
@Test
public void test() throws Exception {
when(myInterfaceMock.doWhatever()).thenReturn("foo");
String result = myClass.doSomething();
...
}
當然,這是不行的,因爲模擬在MyOtherClass並注入不在MyClass中。但是,如果我將它注入MyOtherClass,我沒有MyClass的實例。
編輯:
導致我對這個問題的原因是,我應該做的microService級測試。可能是,我有錯誤的方法。我也可以通過模仿MyOtherClass來測試MyClass,並通過模仿MyInterface來測試MyOtherClass。
所以,這裏是有關給定微服務更詳細一點:
REST的API - > SomeCode - > SomeOtherCode - >其他-REST的API
出代碼覆蓋REST的API,SomeCode和SomeOtherCode。其他-REST-API是第三方,像Google,移動服務提供商等。
現在,我可以使用MockMVC測試REST-API並嘲諷SomeCode。我可以通過嘲笑Other-REST-API來單元測試SomeOtherCode。然而,我的目標是通過使用MockMVC測試整個鏈,做一些參數變化並嘲笑Other-TEST-API,以查看SomeCode和SomeOtherCode的行爲。
我更新了我的解決方案,如果這是您正在尋找的內容,獲得一些反饋將會非常好... –