Mock单元测试和H2内存库的使用

powerMock单元测试_灵耀的博客-CSDN博客讲述了如何使用powermock,本章将同时使用powermock和利用H2进行数据sql测试

依赖

 <properties>
        <mockito.version>2.26.0</mockito.version>
        <powermock.version>2.0.7</powermock.version>
    </properties>
  <!-- mockito jar引入 -->
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <version>${mockito.version}</version>
            <scope>test</scope>
        </dependency>

        <!-- powermock jar引入 -->
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-api-mockito2</artifactId>
            <version>${powermock.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-module-junit4</artifactId>
            <version>${powermock.version}</version>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <artifactId>junit</artifactId>
                    <groupId>junit</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-all</artifactId>
            <version>1.3</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.4.200</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.ninja-squad</groupId>
            <artifactId>DbSetup</artifactId>
            <version>2.1.0</version>
            <scope>test</scope>
        </dependency>

1.1 相关配置

1.1.1 application-context.xml

​
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="Index of /schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jdbc="Index of /schema/jdbc"
xmlns:context="Index of /schema/context"
xsi:schemaLocation="Index of /schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
Index of /schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
Index of /schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<context:component-scan base-package="com.xxx.xx.xxx.xxx.dao;com.baomidou.mybatisplus.core.mapper"/>

<bean id="dataSource" class="org.h2.jdbcx.JdbcConnectionPool"
destroy-method="dispose">
<constructor-arg>
<bean class="org.h2.jdbcx.JdbcDataSource">
<property name="URL" value="jdbc:h2:mem:test;MODE=MySql;DB_CLOSE_DELAY=-1"/>
<property name="user" value="root"/>
<property name="password" value="123456"/>
</bean>
</constructor-arg>
</bean>

<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:h2/grant/mybatis-config.xml"/>
</bean>

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.xxx.xxx.xxx.dsm.dao"/>
</bean>

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg ref="dataSource"/>
</bean>


<jdbc:initialize-database data-source="dataSource" ignore-failures="NONE">
<jdbc:script location="classpath:h2/grant/create-authority.sql"/>
<jdbc:script location="classpath:h2/grant/insert-authority.sql"/>
</jdbc:initialize-database>
</beans>

​

1.2.2 mybatis-config.xml

​
<?xml version="1.0" encoding="UTF-8"?>
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

</configuration>

​

1.3.3 create-authority.sq

CREATE TABLE IF NOT EXISTS authority
(
id bigint(20) NOT NULL AUTO_INCREMENT COMMENT '权限id',
app_id varchar(32) comment '应用id',
name varchar(1024) NOT NULL comment '资源名称(资源表冗余)',
type varchar(20) NOT NULL comment '资源类型(资源表冗余)',
authority_type varchar(20) NOT NULL comment '权限生效类型,更新/新增',
workspace_id varchar(32) NOT NULL comment '所属空间id(资源表冗余)',
resource_id varchar(32) COMMENT '资源id',
auth_content TEXT COMMENT '资权限详细信息源id',
owner varchar(100) NOT NULL comment '权限owner',
owner_type tinyint(1) NOT NULL COMMENT '权限owner type 1.uin,2.role',
op_type varchar(32) comment '权限操作类型',
op_types varchar(200) comment '权限操作类型元数列表',
authority_source tinyint(1) comment '权限获取来源 1.申请,2.授权',
read tinyint(3) NOT NULL DEFAULT '0' COMMENT '资源读权限1.可读,0.不可读',
write tinyint(3) NOT NULL DEFAULT '0' COMMENT '资源写权限1.可写,0.不可写',
admin tinyint(3) NOT NULL DEFAULT '0' COMMENT '资源管理权限1.可管理,0.不可管理',
status tinyint(3) NOT NULL DEFAULT '1' COMMENT '权限状态1.有效,0.无效',
life_cycle varchar(100) NOT NULL COMMENT '权限生命周期',
created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
CONSTRAINT pk_authority PRIMARY KEY(id)

) ;
CREATE UNIQUE INDEX uniq_app_resource_owner_type_status ON authority(app_id, resource_id, owner, owner_type, status);

1.3.4 insert-authority.sql

INSERT INTO authority
(app_id, name, type, authority_type, workspace_id, first_key, second_key, third_key, fourth_key, resource_id, auth_content, owner, owner_type, op_type, op_types, read, write, admin, status, life_cycle, created_at, updated_at)
VALUES('', '', '', '', '', '', '', '', '', '', '', '', 0, '', '', 0, 0, 0, 1, '', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP);

1.2 代码示例和说明

1.2.1 容器启动代码

  • 如果希望数据库走真实逻辑时使用,为了不依赖数据库使用H2内存库
    */


 

import com.ninja_squad.dbsetup.DbSetupTracker;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)
@PowerMockIgnore({"javax.management.*"})
@ContextConfiguration("classpath:h2/grant/application-context.xml")
public class BaseTest1 {

    protected static DbSetupTracker dbSetupTracker;

    @Before
    public void init()  {
        MockitoAnnotations.initMocks(this);
    }

    @BeforeClass
    public static void onceExecutedBeforeAll() {
        dbSetupTracker = new DbSetupTracker();
    }
}


public class AnalyzeOverviewServiceImplTest extends BaseTest1 {

    @InjectMocks
    private AnalyzeOverviewService analyzeOverviewService = new AnalyzeOverviewServiceImpl();

    //这个对象是容器创建的,DAO层代码,根据你的实际情况来
    @Autowired
    private QualityTaskMapper qualityTaskMapper;
   

    @Before
    public void init(){
        //数据库走真是逻辑
        //因为数据库走真是逻辑,因此需要将上面的bean 注入到Mock的对象中
        ReflectionTestUtils.setField(analyzeOverviewService, "qualityTaskMapper",
                qualityTaskMapper);
  
    }

    /**
     * Overview.
     */
    @Test
    public void overview() {
        OverViewDataReq request = new OverViewDataReq();
        request.setEndDate("2021-9-14");
        request.setStartDate("2021-9-14");
        request.setWorkspaceId("123");
        final OverViewDataResp overview = analyzeOverviewService.overview(request);
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值