单元测试——持久层单元测试

主要依赖:

<dependency>

<groupId>junit</groupId>

<artifactId>junit</artifactId>

<version>4.12</version>

</dependency>

 

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-test-autoconfigure</artifactId>

<version>1.4.5.RELEASE</version>

</dependency>

 

<dependency>

<groupId>com.h2database</groupId>

<artifactId>h2</artifactId>

<scope>test</scope>

<version>1.4.194</version>

</dependency>

 

<dependency>

<groupId>org.assertj</groupId>

<artifactId>assertj-core</artifactId>

<version>2.5.0</version>

</dependency>

 

在spring-boot项目中只需要如下依赖:

 

<dependency>

<groupId>com.h2database</groupId>

<artifactId>h2</artifactId>

<scope>test</scope>

<version>1.4.194</version>

</dependency>

 

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-test</artifactId>

</dependency>

 

 

主要代码:

import com.demo.constants.types.DeleteStatus;
import com.demo.domain.entity.DemoEntity;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.UUID;

import static org.springframework.boot.autoconfigure.jdbc.EmbeddedDatabaseConnection.H2;

/**
 * Author: liyang
 * Date: 03/09/2017 10:59 PM
 * Version: 1.0
 * Desc: repository层测试demo,使用内存数据库 h2 进行测试,不会产生脏数据而影响原始库。
 * 推荐使用这种方式进行 repository 测试。
 */
@RunWith(SpringRunner.class)
// 使用 spring-boot-test 提供的jpa测试框架
@DataJpaTest
// 使用 spring-boot-test 提供的默认内存数据库 h2,不需要pom配置自己配置提供的 h2数据库
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE, connection = H2)
public class DemoRepositoryTest {

    @Autowired
    private TestEntityManager entityManager;

    @Autowired
    private DemoRepository demoRepository;

    @Test
    public void findDemoByName() throws Exception {
        // parameters
        String name = UUID.randomUUID().toString();

        // 模拟数据
        DemoEntity demoEntity = new DemoEntity(name);
        entityManager.persist(demoEntity);
        entityManager.flush();

        // 调用服务
        DemoEntity demo = demoRepository.findDemoByName(name);

        // 断言
        Assert.assertTrue(demo.getName().equals(name));
    }
}

被测试方法:

DemoEntity findDemoByName(String name);

配置文件中不需要配置任何跟数据库有关的信息,jpa、hibernate等等都不需要配置。

转载于:https://my.oschina.net/kevin2kelly/blog/1531455

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值