简体   繁体   English

如何为在枚举中声明的 guice 注入 static 变量编写 junit

[英]How to write junit for guice injected static variable which is declared inside Enum

I have enum like this我有这样的枚举

public enum NumbersJk {

    ONE {
        public void processCommand(Info Info) {
            log.info("what is in process " + process)
            process.add(Info);
        }
    },
    TWO {
        public void processCommand(Info Info) {
            process.subtract(Info);
        }
    },
    TEN {
        public void processCommand(Info Info) {
            process.divide(Info);
        }
    }

    @Inject
    private static ProcessNumber process;

    public abstract void processCommand(Info Info) throws Exception;
}

It was injected using guice like this requestStaticInjection(NumbersJk.class);它是使用 guice 注入的,例如requestStaticInjection(NumbersJk.class);

public class AddNumbers {
   public string testMethod(bla,bla,commandToExecute){
      Info info = convert(bla,bla)
      NumbersJk.valueOf(commandToExecute).processCommand(Info);
   }
}

Now I am trying to write junit (powermockito) for this现在我正在尝试为此编写 junit (powermockito)

Junit Junit

@Mock
private ProcessNumber process = new ProcessNumber(new depsencey(), dependecny2());

@InjectMocks
AddNumber addNumber;

@Before
public void setUp() throws Exception {

    MockitoAnnotations.initMocks(this);
}


@Test
@SneakyThrows
public void test() { 
    addNumber.testMethod(1,2,ONE) 
}

This internally calls这在内部调用

NumbersJk.valueOf(commandToExecute).processCommand(Info);

And getting exception java.lang.NullPointerException: null并得到异常java.lang.NullPointerException: null

This is ProcessNumber is coming as null这是ProcessNumber即将作为null

log.info("what is in process " + process) printed as `what is in process null`

Question:问题:

How to inject the class ProcessNumber in junit如何在 junit 中注入 class ProcessNumber

Thanks Jk谢谢Jk

I figured it out.我想到了。 We can use powermock to solve this problem Whitebox.setInternalState(NumbersJk.class, process);我们可以使用powermock来解决这个问题Whitebox.setInternalState(NumbersJk.class, process);

Code:代码:

@Mock
private ProcessNumber process = new ProcessNumber(new depsencey(), dependecny2());

@InjectMocks
AddNumber addNumber;

@Before
public void setUp() throws Exception {
    Whitebox.setInternalState(NumbersJk.class, process);
    MockitoAnnotations.initMocks(this);
}


@Test
@SneakyThrows
public void test() { 
    addNumber.testMethod(1,2,ONE) 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM