-1

I am trying to write tests in spring java.

Classes i have

public class A {

    @Autowired
    private B b;

    public void handle() {
        int xyz = b.call();
    }
}

public class B {

    @Autowired
    private C c;

    public int call() {
        // Do something else here as well.
        return c.callC();
    }
}
public class C {

    @Autowired
    private D d;

    public int callC() {
        //do something with d
        return 123;
    }
}

I want to actually call the class B but want to mock the response from C. Don't know whether it's possible or not.

my test

@SpringBootTest
@RunWith(SpringRunner.class)
public class TestA {

    @Autowired
    private A a;

    @Mock
    private B b

    @Mock
    private C c

    @Test
    public void mytest() {
        when(c.callC()).thenReturn(1);
        A.handle();
        verify(c, times(1)).callC();
    }
}

But it's still actually calling the class C and not mocking it. Any help will be appreciated.

whishky
  • 396
  • 3
  • 13
  • you have not defined what should happen when `b.call` is executed. this code `when(C.callC())` should be `when(c.callC())` – pvpkiran Mar 30 '20 at 15:53
  • @pvpkiran i'll be calling one more class from B and will mock that response as well, so basically i dont want to mock B but i'll mock all the calls which i am making from B. – whishky Mar 30 '20 at 16:37
  • but you have mocked B with this annotation here `@Mock private B b` – pvpkiran Mar 30 '20 at 16:43
  • if you dont want to mock B then Autowire it and not Mock – pvpkiran Mar 30 '20 at 17:06

1 Answers1

0

You’ve got your annotations wrong. If you want to use SpringRunner / SpringExtension:

  • use @MockBean on service you want to mock
  • Use @Autowired to inject services that use them

An alternative is to use Mockito runner and @Mock / @InjectMocks

See Difference between @Mock, @MockBean and Mockito.mock()

Lesiak
  • 22,088
  • 2
  • 41
  • 65
  • and what if i am calling 2 classes from B, and i want to mock one of them and call the other ? – whishky Mar 31 '20 at 06:15
  • Let's assume you want to mock C and have real instance of D. Then provide only `@MockBean` of C, and inject `@Autowired` instance of B or D in case you interact with them from your test class. In fact, your code does not reflect its description - you say "I want to actually call the class B" but you mock it (in an incorrect way). – Lesiak Mar 31 '20 at 06:20