0

Hi i have been struggling a lot with Mokito and after some search on stack overflow and other sources I am still not able to get this. Lets say I have a class B which looks like this :

public class B {
    private String name;
    public String getName(){
        return this.name;
    }
    public void test(){
        String name = getName();
        if (name.equals("S")){
            methodToCall();
        }
    }
    public void methodToCall(){};
}

And my goal is to test if methodToCall gets called if the name is equal to "S" and not called if otherwise. What I have tried is write a another class A which has a method to take a instance of class B like this :

public class A {
    public void publish(B classb){
        classb.test();
    }
}

And then i have a test class defined like this :

public class Test {
    public static void main(String[] args) {
        A a = new A();
        B classb = mock(B.class);
        when(classb.getName()).thenReturn("S");
        a.publish(classb);
        verify(classb, times(1)).methodToCall();

    }
}

my understanding is that when the mock object encounters the method getName, it will return the String "S" that I put in the when nethod and then it should enter the if statement and execute this methodToCall, but the IDE gives me this error:

Exception in thread "main" Wanted but not invoked:
b.methodToCall();
-> at Test.main(Test.java:12)

However, there were other interactions with this mock:
b.test();
-> at A.publish(A.java:3)


    at Test.main(Test.java:12)

I really want to understand what is going on here , and I would appreciate any help. I know that I am having some level of misunderstanding here but if someone can tell me what exactly does this error message mean and why is there in the first place and how to fix it i would be very appreciated. (Note I am not too comfortable with annotations yet so everything is done in a primitive way)

1 Answers1

1

As you mock class B, you mock all of it. Which means you never really run the "test" function, instead you run a mock function of test that does nothing because you didn't tell the mock what to do when you run this function...

If you want the mock to do the real method by calling when(classb.test()).thenCallRealMethod(); but I don't recommend it. Instead, I suggest that you read the following this question about when using mockito at all and ask yourself what class do you want to test.

As a rule of thumb I will just say that if you want to test methods in class B you shouldn't mock class B. Mockito supposed to mock the class dependencies to help you focus on only testing the target class (unitest) without be dependent on the way that other classes behave.

Moshe9362
  • 352
  • 2
  • 15