![](/img/trans.png)
[英]Write junit for a final class using @postconstruct using mockito
[英]JUnit Mockito using a static class final variable
我正在使用 Mockito 為實用程序類編寫 J-unit。 我有另一個常量類,並且使用了一個常量,如下所示:
@Singleton
public class Constants {
public static boolean convertStringtoBoolean(String val) {
return true/false;
}
}
public class MyConstants extends Constants {
public static final boolean flagValue = convertStringtoBoolean("someValue");
}
當應用程序在env
運行時,它會讀取flagValue
。 因此,這是env
具體。 現在我在我的班級中有一個帶有這個標志值的if() condition
。 我想控制這個布爾值。
我可以這樣做嗎? 如果是的話,我怎么能做到這一點。 這是我使用它的方法:
public void myMethod(String, Int) {
if(MyConstant.flagValue){
then do something;
} else {
do this;
}
}
以下是我正在嘗試編寫的測試方法:
public void testMyMethod(){
Constants const = Mockito.mock(Constants.class);
Mockito.when(const.convertStringtoBoolean("some-value")).thenReturn(false);
myMethod(someString, someInt);
}
但我收到以下錯誤:
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);
Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.
Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.
更新:提供了有關代碼和錯誤的更多信息。
你不能用 Mockito 模擬靜態方法。 測試告訴您,您的代碼不像它可能的那樣可測試。 你的類MyConstants
應該有一個方法
public boolean isFlagSet() {
return flagValue;
}
另一個類需要注入MyConstants
class OtherClass {
private final MyConstants myConstants;
OtherClass(
MyConstants myConstants
) {
this.myConstants = myConstants;
}
public void myMethod(String, Int) {
if(myConstant.isFlagSet()){
then do something;
} else {
do this;
}
}
}
在您的測試中,您可以創建MyConstants
的模擬/存根,將其注入OtherClass
並且您的測試testMyMethod
將起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.