舉個栗子(代碼片段):
DemoServiceImpl:
import org.sPRingframework.beans.factory.annotation.Autowired;public class DemoServiceImpl implements DemoService { @Autowired private DemoDao demoDao; @Autowired private StockDao stockDao; /** * 更新庫存 * * @return */ public int updateCount(int id, int count) { //...... UPDATE Database return stockDao.queryStock(id) - count;//返回數量 }}DemoServiceImplAutowireTest:
import mockit.*;import mockit.integration.junit4.JMockit;import org.junit.Assert;import org.junit.Test;import org.junit.runner.RunWith;/** * Autowired對象 Mock測試 */@RunWith(JMockit.class)public class DemoServiceImplAutowireTest { /** * 被測試的對象,只能是具體類,而不能是接口,因為一個接口可能有多個實現類 * 所有帶有@Injectable的實例均被自動注入該實例中 */ @Tested private DemoServiceImpl noteService; /** * 自動注入到noteService中,只有一個StockDao的特定實例stockDao被MOCK掉 */ @Injectable private StockDao stockDao; @Test public void test() { // 1. record 錄制期望值 new Expectations() { { stockDao.queryStock(anyInt);// mock這個方法,無論傳入任何Int類型的值,都返回同樣的值,達到黑盒的效果 result = 50; times = 1; } }; // 2. replay 調用 Assert.assertEquals(50 - 10, noteService.updateCount(1, 10)); //驗證結果 //3.校驗是否只調用了一次。 new Verifications() { { stockDao.queryStock(anyInt); times = 1; } }; }}新聞熱點
疑難解答