@Mock和@InjectMocks的多个级别 [英] Multiple levels of @Mock and @InjectMocks

查看:631
本文介绍了@Mock和@InjectMocks的多个级别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我知道在Mockito中,@ InjectMocks将注入带有@Mock注释的所有内容,但是如何处理这种情况?

So I understand that in Mockito @InjectMocks will inject anything that it can with the annotation of @Mock, but how to handle this scenario?

@Mock
private MockObject1 mockObject1;

@Mock
private MockObject2 mockObject2;

@InjectMocks
private SystemUnderTest systemUnderTest = new SystemUnderTest();

想象一下,MockObject2的属性类型为MockObject1,而SystemUnderTest的属性类型为MockObject2.我想将模拟对象1注入到模拟对象2中,并将模拟对象2注入到systemUnderTest中.

Imagine that MockObject2 has an attribute that is of type MockObject1, and SystemUnderTest has an attribute of type MockObject2. I would like to have mockObject1 injected into mockObject2, and mockObject2 injected into systemUnderTest.

注释是否可行?

推荐答案

由于在这里没有收到任何回复,因此我在Mockito论坛上进行了询问.这是讨论的链接: https://groups.google.com/d /topic/mockito/hWwcI5UHFi0/discussion

Since I didn't get any response here I asked on the Mockito forums. Here is a link to the discussion: https://groups.google.com/d/topic/mockito/hWwcI5UHFi0/discussion

总结答案,从技术上讲,这将使嘲笑的目的失效.您实际上应该只模拟SystemUnderTest类所需的对象.在本身是模拟对象的对象中模拟事物是毫无意义的.

To summarize the answers, technically this would kind of defeat the purpose of mocking. You should really only mock the objects needed by the SystemUnderTest class. Mocking things within objects that are themselves mocks is kind of pointless.

如果您真的想这样做,@ spy可以提供帮助

If you really wanted to do it, @spy can help

这篇关于@Mock和@InjectMocks的多个级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆