spring boot mapper测试类优化
有些时候我们只需要测试在 mybatis 写的mapper 是否正确,在注入mapper的时候,
@SpringBootTest
会启动整个容器,包括servlet容器和spring 容器,随着项目文件数逐渐增加,测试一个类会启动很长时间,所以这次就是实现一个注解,加快我们在spring boot中写mapper测试类时的效率
/*** 针对 mybatis mapper 测试 注解* @description TODO* @date 2024-11-30 21:01*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import({DataSourceAutoConfiguration.class, MybatisPlusAutoConfiguration.class})
//不启动 tomcat 容器
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
@MapperScan
public @interface MapperTest {/*** 指定 spring 容器加载 mapper class** @return*/@AliasFor(annotation = SpringBootTest.class, attribute = "classes")Class<?>[] classes() default {};/*** 指定 mapper 路径** @return*/@AliasFor(annotation = MapperScan.class, attribute = "basePackages")String[] basePackages() default {};/*** 指定 mapper class 扫描** @return*/@AliasFor(annotation = MapperScan.class, attribute = "basePackageClasses")Class<?>[] basePackageClasses() default {};
}
使用
@MapperTest(basePackageClasses = RoleMapper.class, classes = RoleMapper.class)
class ApplicationTests {@Autowiredprivate RoleMapper roleMapper;@Testvoid contextLoads() {RoleModel roleModel = roleMapper.selectById(1l);System.out.println(roleModel);}}
good luck!