[英]Mockito doReturn doesn't return mocked Interface in MVC with singleton
I have A.class to test:我有A.class要测试:
private void register(...) {
...
abcInterface abc = ControllerFactory.getABCController().getABCInterface(); //returns real interface instead of mock
Call<SOMECLASS> call = abc.subscribe(...);
Response<SOMECLASS> response = call.execute();
...
}
ControllerFactory.class is a class where single instance of AbcController
is instantiated. ControllerFactory.class是一个类,其中实例化了AbcController
单个实例。
I have to mock abcInterface
to mock then request and response, and I wrote the following:我必须模拟abcInterface
来模拟然后请求和响应,我写了以下内容:
@RunWith(MockitoJUnitRunner.Silent.class)
public class ATest {
@Mock
AbcInterface AbcInterface;
@Mock
Call<SOMECLASS> request;
@Mock
ControllerFactory controllerFactory;
@Mock
AbcController abcControllerMock;
@Before
public void setup() {
ControllerFactory.createAbcController(); //always single instance is instantiated
}
@Test
public void registerTest() {
Mockito.doReturn(dmsControllerMock).when(controllerFactory).getDmsController();
Mockito.doReturn(abcInterface).when(abcControllerMock).getAbcInterface();
SOMECLASS response = ...
Response<SOMECLASS> response = Response.success(200, response);
Mockito.doReturn(request).when(abcInterface).subscribe(Mockito.any());
Mockito.when(request.execute()).thenReturn(response);
A a = new A(...);
a.register(...);
}
}
The problem is that ControllerFactory.getABCController().getABCInterface();
问题是ControllerFactory.getABCController().getABCInterface();
returns real interface instead of mock.返回真实接口而不是模拟。
It looks like you forgot to mock the getABCController
method, which should return your abcControllerMock
, but instead getABCController
returns an "real" instance of AbcController
which will then return a "real" instance of AbcInterface
.它看起来像你忘了嘲笑getABCController
方法,它应该返回你的abcControllerMock
,而是getABCController
回报的“真实”的实例AbcController
然后将返回一个“真实”的实例AbcInterface
。
So either mock getABCController
or create a constructor for A
that accepts a AbcController and then pass in your mock into that constructor when creating the instance of A
.因此,要么模拟getABCController
要么为A
创建一个接受 AbcController 的构造函数,然后在创建A
的实例时将模拟传递到该构造函数中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.