JUnit4单元测试
1. 引入的jar
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
2. 常用注解
2.1 注解说明
@Before
// 初始化方法,对于每一个测试方式都要执行一次,比如:在单元测试类中有两个单测方法,则在运行测试类时,会执行两次@Before修饰的方式。
@After
// 释放资源,对于每一个测试方式都要执行一次
@BeforeClass
// 针对这个测试类,只执行一次,且必须为 static void
@AfterClass
//针对这个测试类,只执行一次,且必须为 static void
@Ignore
// 忽略该测试方法
2.2 执行顺序
- 在JUnit4单元测试类里执行顺序为 @BeforeClass -> @Before -> @Test -> @After -> @AfterClass
- 在一个单元测试方式中 Before -> @Test -> @After
2.3 示例
执行结果
2.4 断言
Assert.assertEquals(String,String);
Assert.assertNull(Object);
.......
存在很多断言语句
Mocktio单测
1. 引用的jar
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.8.9</version>
<scope>test</scope>
</dependency>
2. 常用注解
2.1 注解说明
@Mock
// mock将测试方法里的某个bean对象mock
@InjectMocks
// 将mock的对象注入到需要测试的类
@RunWith
// 类注解,设置使用哪种runner(运行器)
@ContextConfiguration
// 类注解,设置运行测试方法时,加载那个配置文件
2.2 示例
@RunWith(SpringJUnit4ClassRunner.class)
public class MockitoTest{
@Mock
private ServiceB serviceB;
@InjectMocks
private ServiceA serviceA = new ServiceAImpl();
// 将@mock修饰的对象注入到@InjectMocks修饰的对象中
@Before
public void setUp(){
MockitoAnnotations.initMocks(this);
}
@Test
public void test01(){
// 设置mock的参数,比如当serviceB调用methodB方法时,返回"ceshi"
when(serviceB.methodB()).thenReturn("ceshi");
String methodA = serviceA.methodA();
System.out.println(methodA);
}
}