mardi 26 juillet 2016

Mock a function of class A inside a function of class B [duplicate]

This question already has an answer here:

I have created two classes:
This is class A:

<code>
    public class A {
        public int add(int a) {
             return a + 10;
        }
    }
</code>

This is class B: Say, if I pass x as 10, the 'result' is 100.

<code>
    public class B {
        public int addEnhanced(int x) {
             int result;
             A a = new A();
             int b = a.add(x);
             // something done more.
             return result;
        }
    }
</code>

I am trying to mock a definition in the following way:

<code>
    public class BTest {
        @Before
        public void setup() {
             B b = new B();
        }
        @Test
        public void getEnhancedAdditionResult() {
             A mockA = Mockito.mock(A.class);
             Mockito.when(mockA.add(10)).thenReturn(200);
             int enhancedResult =  b.addEnhanced(10);
             // something more.
        }
    }
</code>

I am trying to do the following: Mock the method 'add' of class A, inside the method 'addEnhanced' of class B.

Above is what I have tried to do the mentioned. But when it runs it gives the result as we have expected to get from: 10, i.e. 100.
But I need to get 200. How do I do that? Please help me correct my code. Code snippets would be helpful.

I will prefer only JUnit and Mockito libraries. No other like PowerMockito. Also, I am new to Mockito.

Thanks. :)

Aucun commentaire:

Enregistrer un commentaire