JUnit4使用Java5中的单元测试

一、JUnit4使用Java5中的注解(annotation)
@Before:初始化方法   对于每个测试方法都要执行一次(注意与BeforeClass区别,后者是对于全部方法执行一次)
@After:释放资源  对于每个测试方法都要执行一次(注意与AfterClass区别,后者是对于全部方法执行一次)
@Test:测试方法,在这里能够测试指望异常和超时时间
@Test(expected=ArithmeticException.class)检查被测方法是否抛出ArithmeticException异常
@Ignore:忽略的测试方法
@BeforeClass:针对全部测试,只执行一次,且必须为static void
@AfterClass:针对全部测试,只执行一次,且必须为static void
一个JUnit4的单元测试用例执行顺序为:
@BeforeClass -> @Before -> @Test -> @After -> @AfterClass;
每个测试方法的调用顺序为:单元测试

@Before -> @Test -> @After;测试

二、执行顺序
随机执行
@FixMethodOrder(MethodSorters.DEFAULT)
public class TestOrder
按testcase名称字符串顺序执行
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class TestOrderthis

三、代码注入Mock
JMokit中的@Mocked与@Injectable区别资源

public class CommonDaoTest {
    @Mock
    private MongoTemplate mongoTemplate;  //注入mongdb mock类,不访问库
    @InjectMocks      //注入的目标类,要实现的test类
    private CommonDao commonDao;文档

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this); //此处必定要记得加上,不然出错
    }字符串

    @Test
    public void dropCollectionName() {
        doNothing().when(mongoTemplate).dropCollection("116");
        commonDao.dropCollectionName("116");    //CommonDao实现了删除文档的功能
    }
}
<dependency>
            <groupId>org.jmockit</groupId>
            <artifactId>jmockit</artifactId>
            <version>1.23</version>
            <scope>test</scope>
</dependency>get

四、各类mock示例
when(systemConfigurationService.getConfiguration(eq(String.class), anyString())).thenReturn("(\\d+\\.*\\d*)");
        when(objService.getKnowledgePointList(anyList())).thenReturn(objectiveKnowledges);
        
when(mongoTemplate.updateFirst(any(Query.class), any(Update.class), anyString())).thenReturn(mock(WriteResult.class));it

when(mongoTemplate.collectionExists("111")).thenReturn(false);io

when(configRepository.findByType(anyString())).thenReturn(mock(Config.class));table