嘗試撰寫模擬測驗,但有一個“for”回圈遍歷映射鍵。我怎么能在測驗方法中初始化地圖。
測驗.java
@ExtendWith(MockitoExtension.class)
public class CartRecordServiceTest {
private MockMvc mockMvc;
private ObjectMapper objectMapper = new ObjectMapper();
@Mock
private CartRecord cartRecords;
@Mock
private GoodsService goodsService;
@Mock
private GoodsRepository goodsRepository;
CartRecordService cartRecordService;
@BeforeEach
public void setUp() {
cartRecordService = new CartRecordService(cartRecords, goodsRepository, goodsService);
mockMvc = MockMvcBuilders
.standaloneSetup(cartRecordService)
.build();
}
@Test
public void checkAvailableTest() {
Map<Long, Long> records = new HashMap<>(Map.of(1L, 2L, 2L, 2L));
Mockito.when(goodsService.enoughQuantity(any())).thenReturn(true);
Assertions.assertTrue(cartRecordService.checkAvailable());
verify(goodsService, times(2)).enoughQuantity(any());
}
}
方法.java
@Service
public class CartRecordService {
private final CartRecord cartRecords;
private final GoodsRepository goodsRepository;
private final GoodsService goodsService;
public CartRecordService(CartRecord cartRecord, GoodsRepository goodsRepository, GoodsService goodsService) {
this.cartRecords = cartRecord;
this.goodsRepository = goodsRepository;
this.goodsService = goodsService;
}
public boolean checkAvailable(){
//here is map
final Map<Long, Long> records = cartRecords.getRecords();
for(Long id : records.keySet()){
if(!goodsService.enoughQuantity(new CartAdditionDTO(id, records.get(id)))){
return false;
}
}
return true;
}
}
日志說:需要但未呼叫:goodsService.enoughQuantity(); -> 在 com.example.store.ServiceUnitTests.CartRecordServiceTest.checkAvailableTest(CartRecordServiceTest.java:117) 實際上,與此模擬的互動為零。
需要但未呼叫:goodsService.enoughQuantity(); -> 在 com.example.store.ServiceUnitTests.CartRecordServiceTest.checkAvailableTest(CartRecordServiceTest.java:117) 實際上,與此模擬的互動為零。
uj5u.com熱心網友回復:
嘗試getRecords()在CartRecord課堂上嘲笑你
Map<Long, Long> records = new HashMap<>(Map.of(1L, 2L, 2L, 2L));
Mockito.when(cartRecords.getRecords()).thenReturn(records);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/359933.html
