0

This is the class structure:

class A {
    private B b;
    A() {
        b = new B();
    }
    public void foo() {
        b.anotherMethod();
    }
}

Test class:

    class TestA {
        @Mock
        B b;
        @Test
        public testFoo() {
            A a = new A();
            when(b.anotherMethod()).thenReturn("something");
            a.foo();
        }
    }

I want to mock object of b, but it's never getting mocked. new B() creates an object of B and real anotherMethod() gets called instead of the thenReturn("something") How can I mock new B() to return mocked object of B so that anotherMethod() doesn't get called?

aaaaa
  • 449
  • 1
  • 5
  • 18
  • That answer is the best place I know to collect the several options you have, but if there's any extra detail that would make that answer inapplicable let me know and I can reopen. – Jeff Bowman Sep 15 '22 at 16:39
  • @JeffBowman I tried PowerMockito.whenNew as suggested for my use case in the above answer. It's not working. Can you please reopen my question? – aaaaa Sep 15 '22 at 17:47
  • Can do, but I would recommend asking a new question. "What are the techniques" and "this technique isn't working" are going to get different answers, and reopening without editing isn't going to help steer folks away from answering like [the question I linked as a dupe](https://stackoverflow.com/questions/27552499/how-to-use-mockito-when-we-cannot-pass-a-mock-object-to-an-instance-of-a-class). – Jeff Bowman Sep 15 '22 at 19:31

0 Answers0