编写一个JPA测试用例

时间:2022-09-11 13:40:37

整合了JPA和mysql需要来测试一下是否可以成功对数据库进行操作,这里写一个简单的单元测试来对之前配置的正确性进行验证。


依赖导入

首先导入需要的SpringTest包和Junit单元测试包。

        <!-- spring-boot-starter-test依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- junit依赖 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>

测试代码

使用如下代码进行测试。
- @SpringBootTest(classes = {Application.class}),使用这个注解并将参数设置为SpringBoot启动类,作用是通过SpringBoot来扫描Bean,以实现自动装配。在1.4之前的版本使用注解@SpringApplicationConfigration
- 使用@Rollback来设置回滚,如果在测试环境,value设为false可以看到事物提交后的数据库。默认为true。在Spring4.2之前使用注解@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)来设置回滚。

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {Application.class})
@Rollback(value = true)
@Transactional(transactionManager = "transactionManager")
public class MysqlTest {
private static Logger logger = LoggerFactory.getLogger(MysqlTest.class);

@Autowired
PlayerRepository playerRepository;
@Autowired
TeamRepository teamRepository;
@Autowired
PositionRepository positionRepository;

@Before
public void initData(){
playerRepository.deleteAll();
positionRepository.deleteAll();
teamRepository.deleteAll();

Team team = new Team();
team.setName("湖人队");
teamRepository.save(team);
Assert.assertNotNull(team.getId());

Position position = new Position();
position.setName("SG");
positionRepository.save(position);
Assert.assertNotNull(position.getId());

Player player = new Player();
player.setName("Kobe Bryant");
player.setCreatedate(new Date());
player.setTeam(team);
List<Position> positions = positionRepository.findAll();
Assert.assertNotNull(positions);
player.setPosition(positions);

playerRepository.save(player);
Assert.assertNotNull(player.getId());
}

@Test
public void findPage(){
Pageable pageable = new PageRequest(0, 10, new Sort(Sort.Direction.ASC, "id"));
Page<Player> page = playerRepository.findAll(pageable);
Assert.assertNotNull(page);

for(Player player: page.getContent()){
logger.info("\n========player======== player name:{}, team name:{}, position name:{}\n",
player.getName(), player.getTeam().getName(), player.getPositions().get(0).getName());
}
}
}