【发布时间】:2020-11-20 05:22:27
【问题描述】:
这样为 Repository 编写 JUnit 测试用例是否正确?同样在运行它时,我在 Mockito.when 行得到 NullPointerException... 这是我的测试课:
@ContextConfiguration(locations = { "classpath*:resources/invoices-context.xml",
"classpath*:resources/invoices-int-schema.xml" })
public class RoomRepositoryTest {
@Autowired
RoomRepository roomRepository;
private RoomEntity roomEntity;
@Test
public void findRommByDateTest() throws ParseException {
String startDate = "27-07-2020";
sDate = new SimpleDateFormat("dd-mm-yyyy").parse(startDate);
String endDate = "28-07-2020";
eDate = new SimpleDateFormat("dd-mm-yyyy").parse(endDate);
String roomType = "SINGLE";
roomEntity = new RoomEntity();
roomEntity.setRoomId(1);
roomEntity.setRoomPrice(6000);
roomEntity.setRoomStatus("AVAILABLE");
roomEntity.setRoomType("SINGLE");
Mockito.when(
roomRepository.findRoomByDate(Mockito.any(Date.class), Mockito.any(Date.class), Mockito.anyString()))
.thenReturn(roomEntity.getRoomId());
int id = roomRepository.findRoomByDate(Mockito.any(Date.class), Mockito.any(Date.class), Mockito.anyString());
assertEquals(1, id);
}
}
【问题讨论】:
-
为什么不应该呢?没有
@RunWith(SpringRunner.class),所以基本上所有的测试都会在你的测试中被忽略,因此会出现空指针异常。 -
即使添加了@RunWith(SpringRunner.class),我仍然收到异常
-
它不能是
null否则你的测试会因为一个错误告诉你它不能被自动连接而中断。另外,如果您自动装配 bean,为什么要使用 Mockito?如果您想模拟为什么要使用自动装配的字段,那么只需模拟它(这将使您的测试无用,因为您没有测试任何东西)。 -
我是新手,这是我第一次为存储库编写 JUnit。那么,除了使用 Mockito 之外,我还可以使用什么替代方式?
-
要么编写集成测试(使用数据库等),要么不为存储库编写测试,模拟它并检查是否返回结果只是模拟框架的测试,而不是你的存储库。
标签: spring-boot junit spring-data-jpa