如何模拟构造函数中的方法调用?

How to mock a method call in a constructor?

我有classclass1,它有2个成员变量:

classA
{
    private Boolean isEnable;
    private Config config;
   
    public classA(final Config config)
    {
        this.config = config;
        isEnable = config.getEnablingStatus();
    }

    public classB fun()
    {
        // Do something!
        // Return an object of classB!
    }
}

我想测试方法 fun,所以我将不得不为此编写一个测试-class 和一个测试方法。但是,如何在创建 classA 类型的对象时模拟方法调用 config.getEnablingStatus()测试 class?

我正在考虑做这样的事情[见下面的代码]。是否正确?但正确的做法是什么?

TestClassForClassA:

TestClassForClassA
{
    private Boolean isEnable;
    
    @Mock
    private Config config;
   
    @InjectMocks
    classA objA = new classA(config);

    @Before
    public void init() 
    {
        initMocks(this);
    }

    public void test1Fun()
    {
        // Does doing this, put the value of isEnable as true in the objA for this test?
        isEnable = true; 
        
        // Here write the code to test the method fun().
    }

    public void test2Fun()
    {
        // Does doing this, put the value of isEnable as false in the objA for this test?
        isEnable = false; 
        
        // Here write the code to test the method fun().
    }
}

不要使用@InjectMocks

尝试这样的事情

public class TestClassForClassA {

    @Mock
    private Config config;

    private ClassA objA;

    @Before
    public void init() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void test1Fun() {
        Mockito.when(config.getEnablingStatus()).thenReturn(true);
        objA = new ClassA(config);
        ClassB objB = objA.fun();
        assertTrue(objB.isEnabled());
    }

    @Test
    public void test2Fun() {
        Mockito.when(config.getEnablingStatus()).thenReturn(false);
        objA = new ClassA(config);
        ClassB objB = objA.fun();
        assertFalse(objB.isEnabled());
    }

}