0

Suppose I have the following class :

public class Math {

    public int mult(int a, int b) {
        return 4;
    }

    public int mul (int a, int b) {
        return mult(a,b);   
    }

}

And the following test class :

public class TestMockito {

    Math testMath;

    @Before
    public void create () {
        testMath = *mock*(Math.class);
        when(testMath.mult(1,2).thenReturn(2);
    }

    @Test
    public void test() {
        System.out.println(testMath.mul(1,2));
    }
}

Why does mul(1,2) called in test() not use when(testMath.mult(1,2).thenReturn(2); ?

Is there any other way to mock a method being used inside another method that is being tested ?

Cheers

2
  • 2
    Here Math is the class under test. you are not suppose to mock the class which is under test. Commented Jun 14, 2017 at 5:17
  • @Jobin Weird. I was learning from : youtube.com/watch?v=79eXGJ2rKZs Commented Jun 14, 2017 at 5:21

1 Answer 1

2

You usually do not mock the code under test (unless it is an abstract class).

You usually mock other classes (the dependencies) your CUT communicates with.

The reason why your test does not work (as you expect) is that the mock is not an object of the real class (which is the reason why we mock it BTW....). It has been derived by the mocking framework not to behave like the original code but like it has been configured for the test.

If you really want the real methods being called in the mock (which is not what you want most of the time) you need to tell mockito that when creating the mock:

mock(ClassToBeMocked.class,Mockito.CALL_REAL_METHODS);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.