Try to write mock test, but there is a 'for' loop which goes through map keys. How could I initialise map at test method.
Test.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());
}
}
Method.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;
}
}
Log says: Wanted but not invoked: goodsService.enoughQuantity(); -> at com.example.store.ServiceUnitTests.CartRecordServiceTest.checkAvailableTest(CartRecordServiceTest.java:117) Actually, there were zero interactions with this mock.
Wanted but not invoked: goodsService.enoughQuantity(); -> at com.example.store.ServiceUnitTests.CartRecordServiceTest.checkAvailableTest(CartRecordServiceTest.java:117) Actually, there were zero interactions with this mock.
CodePudding user response:
Try mocking your getRecords()
on CartRecord
Class
Map<Long, Long> records = new HashMap<>(Map.of(1L, 2L, 2L, 2L));
Mockito.when(cartRecords.getRecords()).thenReturn(records);