简体   繁体   English

如何模拟静态方法设置的最终静态变量?

[英]How to mock a final static variable that is being set by a static method?

I have looked at other questions which are similar to this, but they don't have this exact use case. 我已经查看了与此类似的其他问题,但他们没有这个确切的用例。

If I have code like the following: 如果我有以下代码:

private static final String SOME_CONSANT = SomeStaticClass.getString();

How would I go about mocking this so that it doesn't always return a null pointer exception? 我将如何进行模拟,以便它不会总是返回空指针异常? I have tried the following but it doesn't seem to work. 我尝试了以下但它似乎不起作用。

PowerMockito.mockStatic(SomeStaticClass.class);
when(SomeStaticClass.getString(Mockito.anyString())).thenReturn("test");

I'm at a loss. 我不知所措。 Appreciate any help on this. 感谢任何帮助。

I presume that the main problem of yours is that you are trying to mock different method. 我认为你的主要问题是你试图模仿不同的方法。

With this code when(SomeStaticClass.getString(Mockito.anyString())).thenReturn("test"); 使用此代码when(SomeStaticClass.getString(Mockito.anyString())).thenReturn("test"); you mock method SomeStaticClass.getString(String parameter) , however, in your original code you have SomeStaticClass.getString() . 你模拟方法SomeStaticClass.getString(String parameter) ,但是,在原始代码中你有SomeStaticClass.getString()

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

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