Mocking a method that uses external classes, mockito

前端 未结 2 1287
野的像风
野的像风 2021-01-22 08:05

I\'m new to mockito and just trying to understand how it works.

I have a method that I want to test. The method instantiates multiple classes to use its methods.

2条回答
  •  走了就别回头了
    2021-01-22 08:36

    My standard solution here is to add a method which instantiates the class:

    public ClassToTest {
        methodToTest{
            class1 c1 = newClass1();
            ...
        }
    
        class1 newClass1() {
            return new Class1();
        }
    }
    

    The new method is protected or package private and I simply override it in my unit test to inject the mocks:

    @Test
    public void testFoo() {
        ClassToTest inst = new ClassToTest() {
            class1 newClass1() {
                return new Class1(); // <--- you can mock here
            }            
        };
    }
    

提交回复
热议问题