Home > Back-end >  Mockito - Mock Autowired Service
Mockito - Mock Autowired Service

Time:10-26

I have a Rest Controller class wherein I am autowiring Service Layer. Now I want to mock the service layer in my test class but I get the following exception while running my test class Wanted but not invoked: dbCacheService.refreshCache();

Controller Code

public class AppController {
    @Autowired
    private DbCacheService dbCacheService;

    @GetMapping("/refresh")
    @ApiOperation(value = "Refresh the database related cache", response = String.class)
    public String refreshCache() {
        dbCacheService.refreshCache();
        return "DB Cache Refresh completed";
    }
}

Test Class

@ExtendWith(MockitoExtension.class)
class SmsControllerTest {

    @Mock
    private DbCacheService dbCacheService;

    @BeforeMethod
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    void refreshCache() {
        Mockito.verify(dbCacheService, Mockito.times(1)).refreshCache();
    }
}

I am new to JUnit5 and Mockito. Can someone show me where am I going wrong?

CodePudding user response:

You are not actually calling the Controller method in your test, that is why it is complaining that the call to dbCacheService.refreshCache() never happens. Try the following:

@ExtendWith(MockitoExtension.class)
class SmsControllerTest {

    @Mock
    private DbCacheService dbCacheService;

    @InjectMocks
    private AppController appController;

    @BeforeMethod
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    void refreshCache() {
        appController.refreshCache();
        Mockito.verify(dbCacheService, Mockito.times(1)).refreshCache();
    }
}

Although this might work, this is not the right way to test Controllers. You should test them by actually making an HTTP request and not a method call. In order to do this, you need a slice test with @WebMvcTest:

Something in the line of:

@RunWith(SpringRunner.class)
@WebMvcTest(AppController.class)
public class AppControllerTest {

    @Autowired
    private MockMvc mvc;

    @MockBean
    private DbCacheService dbCacheService;

    @Test
    public void refreshCache() {
        mvc.perform(get("/refresh")
          .contentType(MediaType.APPLICATION_JSON))
          .andExpect(status().isOk())

        Mockito.verify(dbCacheService, Mockito.times(1)).refreshCache();
    }
}
  • Related