Mockito -模拟Autowired服务



我有一个Rest控制器类,其中我自动装配服务层。现在我想在测试类中模拟服务层,但是在运行测试类Wanted but not invoked: dbCacheService.refreshCache();

时出现了以下异常控制器代码

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";
}
}

测试类

@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();
}
}

我是JUnit5和Mockito的新手。谁能告诉我我哪里错了?

您实际上并没有在测试中调用控制器方法,这就是为什么它会抱怨对dbCacheService.refreshCache()的调用从未发生。试试以下命令:

@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();
}
}

虽然这可能有效,但这不是测试控制器的正确方法。您应该通过实际发出HTTP请求而不是方法调用来测试它们。为了做到这一点,您需要使用@WebMvcTest进行切片测试:

  • https://www.baeldung.com/spring-boot-testing unit-testing-with-webmvctest
  • https://rieckpil.de/spring-boot-test-slices-overview-and-usage/

@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();
}
}