我在测试类中遇到问题。
在我的类ParkingSpotService中有一个通过UUID的方法findByid,我想为此编写一个测试:
@Transactional
public Optional<ParkingSpotModel> findById(UUID id) {
return parkingSpotRepository.findById(id);
}
我做了什么?我创建了一个测试类ParkingSpotServiceTest:
@SpringBootTest
public class ParkingSpotServiceTest {
private static final UUID ID = UUID.fromString("35361d85-107c-4f1f-a047-263093161c1b");
private static final String PARKINGSPOTNUMBER = "1010";
private static final String LICENSEPLATECAR = "EAM3J81";
private static final String MODELCAR = "FIT";
private static final String BRANDCAR = "HONDA";
private static final String COLORCAR = "GREEN";
private static final LocalDateTime REGISTRATIONDATE = LocalDateTime.now();
private static final String RESPONSIBLENAME = "Edison Azevedo";
private static final String APARTMENT = "51";
private static final String BLOCK = "A";
@InjectMocks
private ParkingSpotService service;
@Mock
private ParkingSpotRepository repository;
private ParkingSpotModel parkingSpot;
private Optional<ParkingSpotModel> optionalParkingSpot;
Pageable pageable;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
startParkingSpot();
}
private void startParkingSpot() {
parkingSpot = new ParkingSpotModel(ID,
PARKINGSPOTNUMBER,
LICENSEPLATECAR,
BRANDCAR,
MODELCAR,
COLORCAR,
REGISTRATIONDATE,
RESPONSIBLENAME,
APARTMENT,
BLOCK);
optionalParkingSpot = Optional.of(new ParkingSpotModel(ID,
PARKINGSPOTNUMBER,
LICENSEPLATECAR,
BRANDCAR,
MODELCAR,
COLORCAR,
REGISTRATIONDATE,
RESPONSIBLENAME,
APARTMENT,
BLOCK));
}
}
在我创建了一个测试之后
@Test
void whenFindParkingSpotByIDThenReturnAnParkingSpotInstance() {
Mockito.when(repository.findById(Mockito.any(UUID.class))).thenReturn(optionalParkingSpot);
Optional<ParkingSpotModel> response = service.findById(ID);
**//above my response is value = null -> Optional.empty. Why????????**
Assertions.assertNotNull(response);
Assertions.assertEquals(java.util.Optional.class, response.getClass());
Assertions.assertEquals(ID, response.get().getId());
//here my test broke because my response "java.util.NoSuchElementException: No value present"
观察结果:
1.当我检查optionalParkingSpot时,所有数据都在那里。Mockito.when(repository.findById(Mockito.any(UUID.class))).thenReturn(optionalParkingSpot);
1.检查ID时,正确显示UUID(35361 d85 - 107 c-4f 1f-a047 - 263093161 c1 b)Optional<ParkingSpotModel> response = service.findById(ID);
我的“响应”有什么问题?为什么数据是value = null -〉Optional. empty.???
1条答案
按热度按时间dced5bon1#
您确定在您的
@BeforeEach
注解方法中调用的顺序是正确的吗?您首先用MockitoAnnotations.openMocks(this)
初始化mock,然后再初始化应该注入的值?我建议您尝试相反的方法。另外,不要忘记发布https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/InjectMocks.html中描述的模拟
或者,您也可以删除注解并手动插入使用
Mockito.mock(...)
创建的模拟。