Java: Spring: How to mock a method inside Autowired object

375 Views Asked by At
@Component
public class SomeService {

  public void method1() {
  int batchSize = method2();
  // some operations...
  }

  public void method2() {
  // something
  return 10;
  }

Test class

@SpringJUnitConfig(classes = SomeService.class)
public class SomeServiceTests {

  @AutoWired
  SomeService someService;

  @Test
  void method1Test() {
  // mock method2 to return some value instead of executing the method in service

  someService.method1();

  // assertions
  }

when i tried mocking method2 as below i got exception

doReturn(100).when(someService).method2();

Exception

org.mockito.exceptions.misusing.NotAMockException: 
Argument passed to when() is not a mock!
Example of correct stubbing:
    doThrow(new RuntimeException()).when(mock).someMethod();

I understood the exception but not sure how to fix, above shared code is simplified and focusses on issue, my code is bit complex and can't share here due to policies of company.

Thanks for help.

1

There are 1 best solutions below

0
kerbermeister On

Exception means literally what it says. Your service is not a mockito mock and you cannot declare a behaviour on this.

You could use Mockito.spy to, spy or partially mock your service object.

So that you only declare the behavior of second method and execute the actual code for first method.

Or the simpliest way is to use @SpyBean in your case:

@SpyBean
SomeService someService;

And after you'll be able to

doReturn(100).when(someService).method2();