单元测试Mapper文件中的语句

1.添加单元测试的maven依赖

2.创建测试类

3.测试类添加注解

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext_dao.xml","classpath:applicationContext_service.xml"})

classpath:后面的内容是你自己spring的配置文件

4.在测试类中添加测试方法

@Autowired
    ProductInfoMapper productInfoMapper;//mapper的dao接口
    @Test
    public void m1(){
        ProductInfoVo vo=new ProductInfoVo();
        vo.setLprice(1000);
        //vo.setHprice(2000);
        List<ProductInfo> list=productInfoMapper.selectCondition(vo);
        for (ProductInfo productInfo : list) {
            System.out.println(productInfo);
        }
    }

输出结果

5.在mybatis配置文件中添加日志信息

<settings>
    <setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>

输出结果

 

 

在MyBatis,测试资源目录下的Mapper XML文件通常涉及到单元测试。以下是在Spring Boot项目使用`SqlSessionTemplate`或`SqlSession`进行测试的一般步骤: 1. **添加依赖**: 确保在你的pom.xml或build.gradle添加了Spring Test、MyBatis-Spring和MyBatis的测试依赖。 ```xml <!-- Maven --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- Gradle (example) --> testImplementation 'org.mybatis:spring-mybatis:2.0.6' testImplementation 'org.springframework.boot:spring-boot-starter-data-jpa' testImplementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter-test' ``` 2. **配置数据库连接**: 在测试类上添加`@RunWith(SpringRunner.class)`并提供一个数据源或者使用嵌入式H2等内存数据库。 3. **创建SqlSessionFactory**: 使用`SqlSessionFactoryBean`或`SqlSessionAutoConfiguration`自动配置的SqlSessionFactory,注入到测试类。 4. **加载Mapper XML文件**: 使用`SqlSession`的`configurations().getMapper`方法加载Mapper,传入你的Mapper接口的全限定名。 ```java @Autowired private SqlSessionFactory sqlSessionFactory; @Test public void testMapper() { SqlSession sqlSession = sqlSessionFactory.openSession(); try { YourMapper mapper = sqlSession.getMapper(YourMapper.class); // 调用Mapper的方法并验证结果 Object result = mapper.yourMethod(); // 对结果进行断言 } finally { sqlSession.close(); } } ``` 5. **运行测试**: 运行测试类,如果Mapper XML配置无误并且SQL语句正确,测试应该会成功。 注意:记得在`Mapper`接口和`XML`文件之间建立关联,通常是使用`@Mapper`注解和`resource`属性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值