一个start包,它不需要有springboot启动类,它只提供一切公用的功能,被其它包依赖就行了,通过META-INF/spring.factories
或者META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
来自动注入就可以了,我们以mybatis的start包为例,说一下如何进行单元测试。
测试项目结果
两个实体,方便进行事务测试
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("user")
public class User extends BaseEntity {
@TableId(value = "id", type = IdType.ASSIGN_ID)
private String id;
@NotBlank(message = "名称不能为空")
private String username;
}
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("user_attribute")
public class UserAttribute extends BaseEntity {
@TableId(value = "id", type = IdType.ASSIGN_ID)
private String id;
@TableField("user_id")
private String userId;
@NotBlank(message = "名称不能为空")
private String name;
@NotBlank(message = "值不能为空")
private String value;
}
两个mapper类,进行实体持久化
public interface UserMapper extends BaseMapper<User> {
}
public interface UserAttributeMapper extends BaseMapper<UserAttribute> {
}
一个service类,进行事务管理
@Component
public class UserService implements IUserService {
@Autowired
UserMapper userMapper;
@Autowired
UserAttributeMapper userAttributeMapper;
@Transactional(rollbackFor = { Exception.class })
@Override
public void insertUser() {
User user = new User();
user.setId(UUID.randomUUID().toString());
user.setUsername("zzl4");
userMapper.insert(user);
UserAttribute userAttribute = new UserAttribute();
userAttribute.setId(UUID.randomUUID().toString());
userAttribute.setUserId(user.getId());
userAttribute.setName("realName");
userAttribute.setValue("占占");
userAttributeMapper.insert(userAttribute);
}
}
核心测试类,通过手动注入bean,来实现测试mybatis组成的能力
@EnableTransactionManagement表示开启事务;DataSourceTransactionManagerAutoConfiguration是自动注入事务需要的bean
@EnableTransactionManagement
@SpringBootTest(classes = { MybatisAutoConfiguration.class, DataSourceAutoConfiguration.class,
MybatisPlusAutoConfiguration.class, DataSource.class, SqlSessionFactory.class,
DataSourceTransactionManagerAutoConfiguration.class, UserService.class })
@MapperScan(basePackages = "com.lind.common.mybatis.mapper")
public class CurdTest {
@Autowired
UserMapper userMapper;
@Autowired
IUserService userService;
@Test
public void insert() throws IOException {
User user = new User();
user.setId(UUID.randomUUID().toString());
user.setUsername("zzl");
userMapper.insert(user);
}
/**
* @DataSourceTransactionManagerAutoConfiguration 注入事务所需的bean
* @throws IOException
*/
@Test
public void trans() throws IOException {
// 开启事务:@EnableTransactionManagement,注入事务的bean:DataSourceTransactionManagerAutoConfiguration
// 事务需要在新的bean中,不需要在单元测试中直接使用@Transactional
// 使用@Transactional注解都是用在类的方法上。官网也不建议使用在接口类上面,注解肯定都是用到了aop的思想,即使用了动态代理。而如果使用cglib动态代理肯定没有办法代理接口类
userService.insertUser();
}
}