如何使用powermock模拟静态枚举参数

时间:2016-08-01 09:31:25

标签: unit-testing powermock powermockito

我正在使用powermock并遇到两个这样的问题:

public LogUtils {
    public static enum Type {
         **** 
    }

    public void log(Type type, Date date) {
         ***
    }
}

public class Service {
    public int call() {
       LogUtils.log(Type.T1, new Date());
       ***
       return *;
    }
}

@RunWith(PowerMockRunner.class)
public class TestService {
     @Test
     @PrepareForTest(LogUtils.class)
     public void test() {
         Service service = new Service();
         PowerMockito.mockStatic(LogUtils.class);
         LogUtils.log(Type.T1, new Date());  // test here, but failed.
         service.
     }

     @Test
     @PrepareForTest(LogUtils.class)
     public void test2() {
         Service service = new Service();
         PowerMockito.mockStatic(LogUtils.class);
         LogUtils.log(Type.T1, new Date());
         int ret = service.call();
         Assert.isTrue(1, ret);
     }
}

对于test1,它会抛出异常:

java.lang.VerifyError: Bad type on operand stack in arraylength
Exception Details:
  Location:
    LogUtilss$Type.values()[LogUtils$Type; @137: arraylength
  Reason:
    Invalid type: 'java/lang/Object' (current frame, stack[2])
  Current Frame:
    bci: @137
    flags: { }
    locals: { 'java/lang/Object', top, top, top, 'java/lang/Object' }
    stack: { 'java/lang/Object', integer, 'java/lang/Object' }

它是由在类中定义静态枚举而不是直接用单个文件创建枚举引起的。如何解决这个问题,因为我们的代码几乎在类中定义静态枚举?

对于test2,如果第一个问题解决了,可以成功跳过LogUtils.log的直接调用,但是当调用service.call()时,无法跳过。

任何人都可以帮忙吗?非常感谢提前。

我使用powermock 1.6.5和JDK1.7 完整代码示例:

public class LogUtils {

    public static enum Type {
        T(1),
        D(2);

        private int type;

        Type(int type) {
            type = type;
        }
    }

    public static void log(Type t, String msg) {
        System.out.println("skip this method");
    }
}

public class TestAction {

    public void test() {
        String msg = "logMsg";
        LogUtils.log(LogUtils.Type.T, msg);
    }
}

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
public class UnitTest {

    @Test
    @PrepareForTest(LogUtils.class)
    public void test() {
        PowerMockito.mockStatic(LogUtils.class);
        TestAction a = new TestAction();
        LogUtils.log(LogUtils.Type.T, "test");
        a.test();
    }
}

期望:没有'跳过此方法'的打印。

0 个答案:

没有答案