MyBatis 单元测试学习总结
- 依赖
<!-- mybatis测试依赖 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter-test</artifactId>
<version>1.3.2</version>
<scope>test</scope>
</dependency>
- Demo
@RunWith(SpringRunner.class)
@MybatisTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class AgentMapperTest {
@Autowired
private AgentMapper agentMapper;
@Before
public void setUp() throws Exception {
}
@Test
@Rollback
public void testAdd() throws Exception {
Agent agent = new Agent();
agent.setName("auto test");
agent.setIp("127.0.0.1");
agent.setNodeId(0);
agent.setEthernetCard("eth0");
agent.setDatabasePort(3306);
agent.setCreateTime(new Date());
agent.setCreateUser("19044727");
agent.setStatus((byte)1);
int result = agentMapper.insertSelective(agent);
Assert.assertEquals(1,result);
}
@Rollback(false)
@Test
public void testA() throws Exception {
Agent agent = agentMapper.selectByIp("10.47.228.31");
agent.setStatus((byte)1);
agent.setCreateUser("19044727");
int result = agentMapper.updateByPrimaryKeySelective(agent);
Assert.assertTrue(result>0);
}
@Test
public void testSearch() throws Exception {
AgentSearchF searchF = new AgentSearchF();
searchF.setStatus(1);
List<AgentSearchV> list = agentMapper.selectBySearchF(searchF);
Assert.assertNotNull(list);
}
@After
public void tearDown() throws Exception {
}
}
2.1 使用@MybatisTest 默认会使用虚拟的数据源替代你配置的,如果想使用你配置的数据源操作真正的数据库则使用
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
Replace.NONE表示不替换数据源配置
2.2 默认单元测试更新操作默认会回滚,如果你想看到实际数据库表中数据 则添加
@Rollback(false)
表示不回滚