简体   繁体   English

如何模拟注入了模拟的对象的方法

[英]How to mock the method of an object in which mocks are injected

I am writing tests for a class using mockito and testng. 我正在使用Mockito和Testng为类编写测试。 The class to be tested has several dependencies which need to be mocked and injected. 要测试的类具有几个依赖关系,需要对其进行模拟和注入。 The class to be tested has the following profile 要测试的类具有以下配置文件

class A{
    @Autowired
    private Object1;
    @Autowired
    private Object2;
    Object3 methodToBeTested (){
           //some code
           method2();
           //some code
    }
    boolean method2(){
        //some calls to Database that are not operational
    }
}

In my test class, I am declaring the objects Object1 and Object2 as mocks and initializing them as below 在测试类中,我将对象Object1和Object2声明为模拟并将其初始化,如下所示

@Mock
Object1 ob1;
@Mock
Object2 ob2;
@InjectMocks
A a = new A();

@Test
public void ATest(){
     Object3 ob3;
     when(ob1.someMethod()).thenReturn(someObject);
     when(ob2.someMethos()).thenReturn(someOtherObject);
     ob3 = a.methodToBeTested();
     assertNotNull(ob3);
}

The problem arises because I have to mock the call to method2 of class A as well as it has some calls that are not operational in testing phase. 出现问题是因为我必须模拟对类A的method2的调用,并且它包含一些在测试阶段无法运行的调用。 Also mockito does not allow an object to have both @Mocks and @InjectMocks annotations simultaneously. 此外,mockito不允许对象同时具有@Mocks和@InjectMocks批注。 Is there a way to move forward with the testing without modifying code for Class A (don't want to modify it just for testing). 有没有一种方法可以继续进行测试而无需修改A类的代码(不想仅仅为了测试而修改它)。

You need to spy on the real A object, as explained in the documentation : 您需要监视真实的A对象,如文档所述

@Mock
Object1 ob1;

@Mock
Object2 ob2;

@InjectMocks
A a = new A();

@Test
public void ATest(){
    A spy = spy(a);

    doReturn(true).when(spy).method2();

    Object3 ob3;
    when(ob1.someMethod()).thenReturn(someObject);
    when(ob2.someMethos()).thenReturn(someOtherObject);

    ob3 = spy.methodToBeTested();

    assertNotNull(ob3);
}

Note that this has a good chance of indicating a code smell. 请注意,这很有可能表明代码有异味。 The method2() should perhaps be moved into another class, on which A would depend. 可能应该将method2()移到A将依赖的另一个类中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM