mockito 多级@Mock和@InjectMocks

emeijp43  于 2023-06-22  发布在  其他
关注(0)|答案(5)|浏览(250)

所以我知道在Mockito中,@InjectMocks会注入任何它可以用@Mock注解的东西,但是如何处理这种情况呢?

@Mock
    private MockObject1 mockObject1;
    
    @Mock
    private MockObject2 mockObject2;
    
    @InjectMocks
    private SystemUnderTest systemUnderTest = new SystemUnderTest();

假设MockObject2有一个MockObject1类型的属性,SystemUnderTest有一个MockObject2类型的属性。我希望将mockObject1注入到mockObject2,并将mockObject2注入到systemUnderTest
这是可能的注解吗?

uxhixvfz

uxhixvfz1#

因为我在这里没有得到任何回应,我在Mockito论坛上问。下面是讨论的链接:https://groups.google.com/d/topic/mockito/hWwcI5UHFi0/discussion
总结一下答案,从技术上讲,这有点违背了嘲笑的目的。您实际上应该只模拟SystemUnderTest类所需的对象。在对象本身就是被模仿的对象中模仿的东西是毫无意义的。
如果你真的想这样做,@Spy可以帮助你。

cwtwac6a

cwtwac6a2#

可以通过组合@Spy和@InjectMocks来实现。对于您的示例,它将是:

@Spy
private MockObject1 mockObject1 = new MockObject1 ();

@Spy @InjectMocks //if MockObject2 has a MockObject1, then it will be injected here.
private MockObject2 mockObject2 = new MockObject2 ();

@InjectMocks
private SystemUnderTest systemUnderTest;
3ks5zfa0

3ks5zfa03#

我发现的另一个解决方案是使用java sintax代替注解来注入@Spy对象。

@Spy
private MockObject1 mockObject1 = new MockObject1 ();

@InjectMocks //if MockObject2 has a MockObject1, then it will be injected here.
private MockObject2 mockObject2 = spy(MockObject2.class);

@InjectMocks
private SystemUnderTest systemUnderTest;
6tr1vspr

6tr1vspr4#

这对我很有效:

private MockObject1 mockObject1 = mock(MockObject1.class);

@Spy
private RealObject2 realObject = new RealObject2(mockObject1);

@InjectMocks
private SystemUnderTest systemUnderTest = new SystemUnderTest();
a8jjtwal

a8jjtwal5#

以下是我的解决方案:

@ExtendWith(SpringExtension.class)
class DocumentServiceTestMock {

//2nd Level Dependency
CustomerFacade customerFacade = Mockito.mock(CustomerFacade.class);

//Direct Dependency
@Spy
PostCreateHelper postCreateHelper = new PostCreateHelper(customerFacade);

//SUT
@InjectMocks
DocumentService documentService;

@BeforeEach
void setUp() {
        given(customerFacade.getString()).willReturn("customerFacade_MOCKED");
}

@Test
void test() {
     String documentAsResource = documentService.getDocumentAsResource(ExportType.WORD);
}
//----------
@Service
public class DocumentService {
   final PostCreateHelper postCreateHelper;

@Component
public class PostCreateHelper {
   final CustomerFacade customerFacade;

@Service
public class CustomerFacade {

相关问题