我有一個 Rest Controller 類,我在其中自動裝配服務層。現在我想在我的測驗類中模擬服務層,但是在運行我的測驗類時出現以下例外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 的新手。有人可以告訴我我哪里出錯了嗎?
uj5u.com熱心網友回復:
您實際上并沒有在測驗中呼叫 Controller 方法,這就是為什么它抱怨呼叫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();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/336053.html
