Mockito. How to return a boolean value based on mocked object as parameter?

15,396

The other answers are technically correct, but the first thing to understand: you should strive to not use a mocking framework like this.

Keep in mind: the purpose of a mocking framework is only to make testing possible/easier. Your mocking specs should be as simple as possible. Meaning: instead of thinking about having a mock giving different results on different parameters - the better solution is to have distinct tests and mocking specs, like:

@Test 
public void testFooWithA() {
  when(someMock.foo(eq(whateverA)).thenReturn(bar);
  ...

@Test 
public void testFooWithB() {
  when(someMock.foo(eq(whateverB)).thenReturn(somethingElse);
  ...

There are situations where you have write more sophisticated code to make your mocks "more smart". But most of the time when I had to do that - I stepped backed, and simplified my design under test. In other words: when your tests turn "too complicated" - most often the reason is a too complicated class/method under test.

Share:
15,396
Ankit Basarkar
Author by

Ankit Basarkar

Updated on July 19, 2022

Comments

  • Ankit Basarkar
    Ankit Basarkar over 1 year
    Class A
    {
    public B makeB(int q)
        {
            return new B(q);
        }
        public boolean evaluate(int q)
        {
            B b = makeB(q);
            boolean result = b.get();
            return result;
        }
    }
    
    Class B
    {
        int e;
        public B(int w)
        {
            e=w;
        }
        public boolean get()
        {
            //return boolean based on object B
        } 
    }
    
    Class ATest
    {
        A a = spy(A.class);
        B b1 = mock(B.class);
        B b2 = mock(B.class);
    
        doReturn(b1).when(a).makeB(5);
        doReturn(b2).when(a).makeB(10);
    
        when(b1.get()).thenReturn(true);
        when(b2.get()).thenReturn(false);
    
        a.evaluate();
    }
    

    =======================

    Here I would like to return true from method evaluate when object B contains value 5 and false if it contains value 10.

    Class B is from an external Library.

    New to unit testing and mockito.