我有@Component一个注入对象的追随者,它进行链式方法调用以获取某些东西,例如@Componentpublic class MyInterceptor implements ClientHttpRequestInterceptor { @Autowired public MyProducer producer; @Override public ClientHttpResponse intercept(…) throws IOException { String val = producer.getProducer().getSomeVal(/*parameters*/); // LINE (1) }}我的测试类是:@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes = { MyInterceptor.class, MyProducer.class } )public class MyInterceptorTest { private RestTemplate restTemplate = new RestTemplate(); private MockRestSErviceServer mockServer; @Rule public MockitoRule rule = MockitoJUnit.rule(); @Mock public MyProducer producer; @InjectMocks private MyInterceptor interceptor; @Before public void init() { //MockitoAnnotation.initMocks(this); producer = Mockito.mock(MyProducer.class, Mockito.RETURNS_DEEP_STUBS); // adding interceptor to RestTemplate mockServer = MockRestServiceServer.createServer(restTemplate); when(producer.getProducer().getSomeVal(null, null)).thenReturn("SomeValue"); } @Test public void myTestMethod() { mockServer.expect(requestTo(/*some dummy URL*/) .andExpect(method(HttpMethod.GET)) .andExcept(/*some header stuff omitted from MyInterceptor */) .andRespond(withSuccess(/*…*/)); // This is going to trigger the Interceptor being invoked restTemplate.getForEntity("some dummy URL", String.class); // LINE (2) mockServer.verify(); }}当测试执行 LINE (2) 并调用拦截器时,在 LINE (1) 中我得到一个空指针异常。我假设通过在模拟上启用深度存根,我将能够进行链式调用并获得预期值,例如,producer.getProducer().getSomeVal()但事实并非如此。你知道我怎样才能让这个按预期工作吗?PS 我已经尝试了添加MockitoAnnotation.initMocks()和删除的不同变体@Rule,或者只是@Autowired MyInterceptor在测试类中尝试了这导致MyProducer根本不会被嘲笑,但似乎没有任何效果。注意,MyProducer不能修改,因为它来自另一个项目。
1 回答

白猪掌柜的
TA贡献1893条经验 获得超10个赞
你嘲笑了MyProducer
类,但你没有提供when
for producer.getProducer()
。
因此,当代码调用时,producer.getProducer()
它将返回默认的模拟值,即 null。
您可以尝试几种不同的方法:
when(producer.getProducer()).thenReturn(producer);
我不确定这是否行得通——可能行得通。
否则,您可以编写一个本地测试类来实现/扩展 getProducer() 返回的任何内容,当正确的参数传递给getSomeVal()
.
添加回答
举报
0/150
提交
取消