尝试编写测试,使用模拟进行操作。当断言发生时,就会出现异常。
CardRecordServiceTest.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 enougthGoodsToAddRecordNew(){
CartAdditionDTO cartAdditionDTO = new CartAdditionDTO(1L, 15L);
Mockito.when(goodsService.enoughQuantity(cartAdditionDTO)).thenReturn(true);
Mockito.when(cartRecords.getRecords()).thenReturn(Map.of(2L,2L));
Assertions.assertTrue(cartRecordService.addRecord(cartAdditionDTO));
verify(cartRecords,times(2)).getRecords();
verify(goodsService).enoughQuantity(any(CartAdditionDTO.class));
}
Run Code Online (Sandbox Code Playgroud)
CartRecordService.java
public boolean addRecord(CartAdditionDTO cartAdditionDTO) {
if(!goodsService.enoughQuantity(cartAdditionDTO)){
return false;
}
if (cartRecords.getRecords().containsKey(cartAdditionDTO.getId())) {
Long newQuantity = cartRecords.getRecords().get(cartAdditionDTO.getId()) + …Run Code Online (Sandbox Code Playgroud)