user2957954
user2957954

Reputation: 1249

Mocking one method with different values

I still have some difficulties with Mockito. I want to have two test cases for two different object examples. So I want to simulate different method behaviour depending on argument value.

The problem is that when I run test() method, the returned value of help valiable is "b" and the assertion doesn't return true. If I comment the line marked as (***), everything works fine.

As you can see I tried to use thenAnswer instead of thenReturn, but the result was the same.

public class TestItAll {
      TestClass test;

      HelpClass a ;
      HelpClass b;

      @Before
      public void init(){

          a = new HelpClass("a");
          b = new HelpClass("b");

          Mockito.when(test.getHelp(a)).thenReturn("a");
          /*Mockito.when(test.getHelp(a)).thenAnswer(
            new Answer< String>() {
                  public String answer(InvocationOnMock invocation) {
                      return "a";
                  }
            });         */
          Mockito.when(test.getHelp(b)).thenReturn("b");//(***)

          /*Mockito.when(test.getHelp(b)).thenAnswer(
            new Answer< String>() {
                  public String answer(InvocationOnMock invocation) {
                      return "b";
                  }
            });         */
      }


      @Test
      public void testA(){
          String help= test.getHelp(a);
          Assert.assertEquals(help, "a");
      }

      /*@Test
      public void testB(){
          String help= test.getHelp(b);
          Assert.assertEquals(help, "b");
      }*/
}

Please, don't ask me why I'm mocking a test object. It's just a model example of a more complicated situation.

Upvotes: 0

Views: 387

Answers (1)

Jaroslaw Pawlak
Jaroslaw Pawlak

Reputation: 5588

Firstly, I assume that your declaration TestClass test; is in fact TestClass test = mock(TestClass.class);, otherwise the @Before method throws NullPointerException.

When using when(test.getHelp(a)) mockito will use a's equals method to check whether the parameter matched. If e.g. equals method always returns true, it won't be able to differ a from b. I have run your code with overriding equals method (i.e. HelpClass objects are equal only if they are the same instance) and both tests have passed.

You may want to use argument matcher - when(test.getHelp(argThat(sameInstance(a)))) to not rely on your equals method. If you need something more complex than sameInstance, I would recommend sameBeanAs matcher from shazamcrest.

Upvotes: 2

Related Questions