MyBatis 單元測試學習總結

  1. 依賴
<!-- mybatis測試依賴 -->
<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter-test</artifactId>
	<version>1.3.2</version>
	<scope>test</scope>
</dependency>
  1. 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)

表示不回滾

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章