单元测试研究
(testng + jmockit + springboot)
环境配置可以参考最下面的参考资料,其中已经非常清晰了。这里不再描述了
引入spring自动配置
- 利用spingTesting 直接使用@ContextConfiguration
//1.ContextConfiguration中注入所需要的类,由于UserServiceImpl中@Autowired了UserInfoDao、AccountDao、 OssConfig,所以都需要注入。
@ContextConfiguration(classes = {UserServiceImpl.class, UserInfoDaoImpl.class,
AccountDaoImpl.class, OssConfig.class})
//2.需要继承AbstractTestNGSpringContextTests类
public class UserServiceImplTest extends AbstractTestNGSpringContextTests {
@Autowired
private UserServiceImpl serviceInterface;
@Test
public void testSpringAutoConfig(){
Person abc = serviceInterface.getUserInfoByName("abc");
System.out.println(abc);
}
}
//3. UserServiceImpl、UserInfoDaoImpl、AccountDaoImpl修饰@Component
- 利用配置类@Configuration结合@ContextConfiguration
利用一个配置类config.java配置完依赖之后,利用
@ContextConfiguration(classes = Config.class),其他操作和1一样。 - 利用springBootTesting
@SpringBootTest(classes = {UserServiceImpl.class, UserInfoDaoImpl.class,
AccountDaoImpl.class, OssConfig.class})
public class UserServiceImplTest extends AbstractTestNGSpringContextTests {
@Autowired
private UserServiceImpl serviceInterface;
@Test
public void testSpringAutoConfig(){
Person abc = serviceInterface.getUserInfoByName("abc");
System.out.println(abc);
}
}
其他和@ContextConfiguration一样,springboottest也可以使用@Configuration方式
4. 可以使用@SpringBootConfiguration(没有研究跳过)
5. 使用@ComponentScan扫描Bean,前面都是使用@SpringBootTest或@ContextConfiguration(classes = {….})装配bran,还可以使用@ComponentScan去扫描指定路径
@SpringBootTest
@ComponentScan(basePackages = "com.dullbird")
//其中使用@SpringBootTest(classes = {OssConfig.class})或者@ContextConfiguration总是获取不到配置文件的值,但是使用ComponentScan可以获取到。
//OssConfig 类如下
@Component
@ConfigurationProperties(prefix = "oss")
p