mockito、easymock、powermock使用(5)-静的方法試験

2420 ワード

目的
静的方法テストコードを作成し、静的方法コードの実行結果をシミュレーションします.
準備工作
mockito、easymock、powermock使用(2)-準備作業
テストコード
import cn.suning.util.DateUtil;
import com.suning.work.controller.MockController;
import com.suning.work.service.MockService;
import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatchers;
import org.mockito.InjectMocks;
import org.mockito.Mock;
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 javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;


@RunWith(PowerMockRunner.class)
/**
 *        
 */
@PrepareForTest(DateUtil.class)
@PowerMockIgnore("javax.management.*")
public class MockStaticMethodTest {

    @InjectMocks
    MockController mockController;

    @Mock
    MockService mockService;

    HttpServletRequest request;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
        request = (HttpServletRequest) EasyMock.createMock(HttpServletRequest.class);
        // mock    
        PowerMockito.mockStatic(DateUtil.class);
    }

    @Test
    public void test() {
        Map map=null;

        //           
        PowerMockito.when(DateUtil.format(ArgumentMatchers.anyString(),ArgumentMatchers.any(Date.class))).thenReturn("2018-12-12 12:12:12");
        map=mockController.geStaticDate(request);
        System.out.println(map.get("obj"));

        //           
        PowerMockito.when(DateUtil.format(ArgumentMatchers.anyString(),ArgumentMatchers.any(Date.class))).thenReturn("2018-18-18 18:18:18");
        map=mockController.geStaticDate(request);
        System.out.println(map.get("obj"));
    }

}
シミュレーション説明
/** * 静的クラスの宣言 */@PrepareForTest(DateUtil.class)
/**
 * mock    
 */
PowerMockito.mockStatic(DateUtil.class);
//           
PowerMockito.when(DateUtil.format(ArgumentMatchers.anyString(),ArgumentMatchers.any(Date.class))).thenReturn("2018-12-12 12:12:12");
シミュレーション結果
2018-12-12 12:12:12
2018-18-18 18:18:18