1、JMockit配置
<!-- 先聲明jmockit的依賴 -->
<dependency>
<groupId>org.jmockit</groupId>
<artifactId>jmockit</artifactId>
<version>1.36</version>
<scope>test</scope>
</dependency>
<!-- 再聲明junit的依賴 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.9</version>
<scope>test</scope>
</dependency>
注:如果通過mvn test來運行你的測試程序 , 請確保JMockit的依賴定義出現在JUnit的依賴之前。
2、程序結構案例:
//JMockit的程序結構
public class ProgramConstructureTest {
// 這是一個測試屬性
@Mocked
HelloJMockit helloJMockit;
@Test
public void test1() {
// 錄製(Record)
new Expectations() {
{
helloJMockit.sayHello();
// 期待上述調用的返回是"hello,david",而不是返回"hello,JMockit"
result = "hello,david";
}
};
// 重放(Replay)
String msg = helloJMockit.sayHello();
Assert.assertTrue(msg.equals("hello,david"));
// 驗證(Verification)
new Verifications() {
{
helloJMockit.sayHello();
times = 1;
}
};
}
@Test
public void test2(@Mocked HelloJMockit helloJMockit /* 這是一個測試參數 */) {
// 錄製(Record)
new Expectations() {
{
helloJMockit.sayHello();
// 期待上述調用的返回是"hello,david",而不是返回"hello,JMockit"
result = "hello,david";
}
};
// 重放(Replay)
String msg = helloJMockit.sayHello();
Assert.assertTrue(msg.equals("hello,david"));
// 驗證(Verification)
new Verifications() {
{
helloJMockit.sayHello();
// 驗證helloJMockit.sayHello()這個方法調用了1次
times = 1;
}
};
}
}
JMockit的程序結構包含了測試屬性或測試參數,測試方法,測試方法體中又包含錄製代碼塊,重放測試邏輯,驗證代碼塊。
3、Jmockit API
@Mocked
該註解修飾的類/接口,是讓Jmockit生成對象,這個對象方法(包含靜態對象)返回默認值。
@Injectable
該註解也是讓Jmockit生成對象,但@Injectable只是針對其修飾的實例,而@Mocked是針對其修飾類的所有實例。此外,@Injectable對類的靜態方法,構造函數沒有影響。因爲它隻影響某一個實例嘛!
@Tested
該註解表示被測試對象,如果該對象沒有賦值,則實例化它。若@Tested的構造函數有參數,
則JMockit通過在測試屬性&測試參數中查找@Injectable修飾的Mocked對象注入@Tested對象的構造函數來實例化,
不然,則用無參構造函數來實例化。除了構造函數的注入,JMockit還會通過屬性查找的方式,把@Injectable對象注入到@Tested對象中。
例子如下:
//@Tested與@Injectable搭配使用
public class TestedAndInjectable {
//@Tested修飾的類,表示是我們要測試對象,在這裏表示,我想測試訂單服務類。JMockit也會幫我們實例化這個測試對象
@Tested
OrderService orderService;
//測試用戶ID
long testUserId = 123456l;
//測試商品id
long testItemId = 456789l;
// 測試注入方式
@Test
public void testSubmitOrder(@Injectable MailService mailService,
@Injectable UserCheckService userCheckService) {
new Expectations() {
{
// 當向testUserId發郵件時,假設都發成功了
mailService.sendMail(testUserId, anyString);
result = true;
// 當檢驗testUserId的身份時,假設該用戶都是合法的
userCheckService.check(testUserId);
result = true;
}
};
// JMockit幫我們實例化了mailService了,並通過OrderService的構造函數,注入到orderService對象中。
//JMockit幫我們實例化了userCheckService了,並通過OrderService的屬性,注入到orderService對象中。
Assert.assertTrue(orderService.submitOrder(testUserId, testItemId));
}
}
參考文章:http://jmockit.cn/showArticle.htm?channel=2&id=3