最近在寫單元測試的時(shí)候,出了用到了比較常用的mockito和powermock外(關(guān)于這兩個(gè)工具的用法舰绘,可以參看這篇博客)蹂喻,還有用的一些其他的比較好用的工具類。
第一個(gè)就是Junit中了@Rule注解捂寿,它就像@Before口四,@After這些腳手架的注解一樣,為了測試方法添加一些前置行為秦陋。例如為所有的測試添加一個(gè)timeout時(shí)間:
public class BlahTest {
@Rule
public Timeout timeout = new Timeout(2000);
@Test
public void testA() throws Exception {
// ...
}
@Test
public void testB() throws Exception {
// ...
}
}
或者創(chuàng)建一個(gè)臨時(shí)目錄:
public class BlahTest {
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
@Test
public void testIcon() throws Exception {
File icon = tempFolder.newFile("icon.png");
// do something else...
}
}
在我的測試了蔓彩,我主要是用來的測試被測方法中的異常,通過使用@Rule,不但可以測試方法中的異常類型赤嚼,還可以驗(yàn)證異常的message:
public class BlahTest {
@Rule
public ExpectedException exception = ExpectedException.none();
@Test
public void testIcon() throws Exception {
exception.expect(IllegalArgumentException.class);
exception.expectMessage("Dude, this is invalid!");
// do something that you expect to throw an exception...
}
}
同樣用也可以定義自己的Rule旷赖,更多關(guān)于Junit Rule的東西,可以參看相關(guān)的wiki探膊。
另一個(gè)比較有意思的工具就是Spring 4.2提供了ReflectionTestUtils杠愧,當(dāng)被測試類中需要注入Spring Bean的時(shí)候,就可以使用這個(gè)工具類:
本測試類
public class Blah {
@Autowired
private BlahDao blahDao
public void someMethod() {
blahDao.callMethod();
//do someting others
}
}
測試方法
@Test
public void testMethod() {
BlahDao mockBlahDao = createMock(BlahDao.class);
ReflectionTestUtils.setField(blah, "blahDao", mockBlahDao);
......
}
在我的測試用逞壁,因?yàn)槭褂昧薽ockito流济,所有通過@InjectMocks注解就可以實(shí)現(xiàn)Bean的注入,但對于@Value這樣的屬性注入腌闯,就只能使用ReflectionTestUtils了绳瘟。
@Value("${importedFile.baseDir}")
private String baseDir;
ReflectionTestUtils.setField(testedClass, "baseDir", "/opt/xxxx/")