简体   繁体   中英

How to mock a local variable b (which uses private method) without using power mockito?

public class A {
    public void methodOne(int argument) {
        //some operations
        B b = methodTwo(int argument);

        // some operations based on b
        // switch cases based on returned values of b

    }

    private void methodTwo(int argument)
    DateTime dateTime = new DateTime();
    //use dateTime to perform some operations
}

Ideally, you don't!

Meaning: your methodOne() is returning a certain value. So, if possible, you should prefer to not test internals.

Thus, you should write test cases that invoke methodOne() with various parameters; and then assert that the value returned by that method matches your exceptions.

If you really need to control that "B" object in order to do reasonable testing, the correct way to get there is to use dependency injection and provide a B object to your class under test somehow. Because then you can create a mocked B and hand that to your class under test.

In other words: learn how to write testable code; for example by watching these videos . Seriously; each minute of that material is worth your time.

If you really must mock class B , then you can do it as follows (without using PowerMock, but instead the JMockit library):

public class ExampleTest {
    @Tested A a;

    @Test
    public void exampleTest(@Mocked B anyB) {
        // Record calls to methods on B, if/as needed by code under test:
        new Expectations() {{ anyB.doSomething(); result = "mock data"; }};

        // Exercise the code under test:
        a.methodOne(123);

        // Verify a call to some other method on B, if applicable:
        new Verifications() {{ anyB.someOtherMethod(anyString, anyInt); }};
    }
}

Note this test does not care how A obtains B . It is independent of implementation details such as private methodTwo , as a good test should always be.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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