Question

I want to mock a method which is in different project.

Assume I have a method call addNumbers() in the Project JUnitDemo. I am calling the method calculate() which is in another project call JunitDemoMock.

public final int addNumbers(int num1)
    {

        Calculator calculator = new Calculator();
        int num2 = calculator.calculate(); total = num1 + num2;
        return total;
    }

Now I want to mock the calculate() method in my unit test. I am doing like this.

@RunWith(PowerMockRunner.class)
@PrepareForTest({Calculator.class})
public class MockDemoTest
{

    /**
     * Test method for {@link com.nyl.mock.MockDemo#addNumbers(int)}.
     * 
     * @throws Exception
     */
    @Test
    public void testAddNumbers() throws Exception
    {

        // Mock only the calculate method
        Calculator tested =
                PowerMock.createPartialMock(Calculator.class, "calculate");

        // Expect the private method call to "calculate"
        PowerMock.expectPrivate(tested, "calculate").andReturn(89);
        PowerMock.replay(tested);

        MockDemo mockDemo = new MockDemo();
        assertEquals(10, mockDemo.addNumbers(3));
        //PowerMock.verify(tested);
    }

}

But here actual mocking is not happening. The method calculate() will execute during the run time. Can any one please tell me why this is happening and how can we mock the calculate() correctly.

Note: If we have the calculate() method in the same project I mean in JUnitDemo the mocking is working fine.

Lib versions

cglib-nodep-2.2.2.jar, easymock-3.1.jar, javassist-3.18.0-GA.jar, junit-4.7.jar, objenesis-1.2.jar, powermock-easymock-1.5.1-full.jar,

Was it helpful?

Solution

Not sure but don't you need to set Mock instance in MockDemo like

MockDemo mockDemo = new MockDemo();
mockDemo.setCalculator(tested);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top