天天看點

mockito、easymock、powermock使用(7)-whenNew使用

目的

編寫whenNew測試代碼,模拟建立對象其方法的執行結果

準備工作

mockito、easymock、powermock使用(2)-準備工作

測試代碼

import com.suning.work.controller.MockController;
import junit.framework.TestCase;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.io.File;

@RunWith(PowerMockRunner.class)
@PowerMockIgnore("javax.management.*")
public class MockWhenNewTest extends TestCase {
    @InjectMocks
    MockController mockController;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
    }

    /**
     * 當使用PowerMockito.whenNew方法時,必須加注解@PrepareForTest和@RunWith。
     * 注解@PrepareForTest裡寫的類是需要mock的new對象代碼所在的類
     *
     * PrepareForTest 可以寫在測試類或測試函數上效果一樣
     * @throws Exception
     */
    @Test
    @PrepareForTest(MockController.class)
    public void test() throws  Exception {

        File file = PowerMockito.mock(File.class);
        //模拟建立新對象的傳回值
        PowerMockito.whenNew(File.class).withArguments("system.properties").thenReturn(file);
        //模拟方法的結果
        PowerMockito.when(file.exists()).thenReturn(true);
        boolean result= mockController.fileExist("system.properties");
        System.out.println(result);

        PowerMockito.when(file.exists()).thenReturn(false);
        result= mockController.fileExist("system.properties");
        System.out.println(result);
    }
}
           

測試說明

/**
 * 當使用PowerMockito.whenNew方法時,必須加注解@PrepareForTest和@RunWith。
 * 注解@PrepareForTest裡寫的類是需要mock的new對象代碼所在的類
 *
 * PrepareForTest 可以寫在測試類或測試函數上效果一樣
 */
@PrepareForTest(MockController.class)      
//模拟建立新對象的傳回值
PowerMockito.whenNew(File.class).withArguments("system.properties").thenReturn(file);
//模拟方法的結果
PowerMockito.when(file.exists()).thenReturn(true);      

測試結果

true
false
           

繼續閱讀