mockito、easymock、powermock使用(5)-静态方法测试

目的

编写静态方法测试代码,模拟静态方法代码的执行结果

准备工作

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

 

你可能感兴趣的:(代码质量)