单元测试遇到的坑

  1. 使用Mockito来来模拟外部依赖的对象,完成单元测试。结果发现when(mock.someMethod()).thenReturn 对static修饰的方法是无法设置方法调用的预期返回,与我所需的单元测试不符合。遂改用PowerMockito,PowerMock扩展了EasyMock和Mockito框架,增加了对static、final和pricvate方法mock支持等功能。

  2. 改用PowerMockito:
    PowerMockito.mockStatic(HttpTest.class);
    PowerMockito.when(HttpTest.doPost(requestOc,request,1000*20)).thenReturn(response);
    报错为:
    org.powermock.api.mockito.ClassNotPreparedException:
    The class com.sf.cx.util.HttpTest not prepared for test.
    To prepare this class, add class to the ‘@PrepareForTest’ annotation.
    In case if you don’t use this annotation, add the annotation on class or method level.
    解决办法是加上,@RunWith(PowerMockRunner.class) @PrepareForTest(HttpTest.class)

    这是PowerMock的两个重要的注解:
    @RunWith(PowerMockRunner.class)语句告诉JUnit用PowerMockRunner来执行测试。
    @PrepareForTest(Employee.class)语句告诉PowerMock准备Employee类进行测试。适用于模拟final类或有final, private, static, native方法的类。

你可能感兴趣的:(java)