舉個(gè)栗子(代碼片段):
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;//返回?cái)?shù)量 }}DemoServiceImplAutowireTest:
import mockit.*;import mockit.integration.junit4.JMockit;import org.junit.Assert;import org.junit.Test;import org.junit.runner.RunWith;/** * Autowired對(duì)象 Mock測試 */@RunWith(JMockit.class)public class DemoServiceImplAutowireTest { /** * 被測試的對(duì)象,只能是具體類,而不能是接口,因?yàn)橐粋€(gè)接口可能有多個(gè)實(shí)現(xiàn)類 * 所有帶有@Injectable的實(shí)例均被自動(dòng)注入該實(shí)例中 */ @Tested private DemoServiceImpl noteService; /** * 自動(dòng)注入到noteService中,只有一個(gè)StockDao的特定實(shí)例stockDao被MOCK掉 */ @Injectable private StockDao stockDao; @Test public void test() { // 1. record 錄制期望值 new Expectations() { { stockDao.queryStock(anyInt);// mock這個(gè)方法,無論傳入任何Int類型的值,都返回同樣的值,達(dá)到黑盒的效果 result = 50; times = 1; } }; // 2. replay 調(diào)用 Assert.assertEquals(50 - 10, noteService.updateCount(1, 10)); //驗(yàn)證結(jié)果 //3.校驗(yàn)是否只調(diào)用了一次。 new Verifications() { { stockDao.queryStock(anyInt); times = 1; } }; }}新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注