lundi 1 août 2016

how to mock static enum parameter using powermock

I am using powermock and meet two problems like this:

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);
     }
}

For test1, it would throw Exception:

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' }

it is caused by defining static enum in class instead of directly creating enum with single file. How to solve this problem as our codes almost define static enum in class?

For test2, if the first problem is solved, the direct call of LogUtils.log could be successfully skipped, but when call service.call(), couldn't skip.

Anyone could kindly help on this? Thanks a lot in advance.

Aucun commentaire:

Enregistrer un commentaire