Во время насмешки над статическим методом с PowerMockito, я получаю исключение незавершенной заглушки - PullRequest
0 голосов
/ 10 октября 2018

Ниже мой код.У меня есть два класса

1)
public class AdminUtil {
 public static boolean isEnterpriseVersion() {
        return SystemSettings.getInstance().isEnterpriseVersion();
    }
}
----
2)
public class SystemSettings {
public static synchronized SystemSettings getInstance() {
        if (systemSettings == null) {
            systemSettings = new SystemSettings();
        }
        return systemSettings;
    }
}

И вот как я пытаюсь смоделировать метод isEnterpriseVersion () класса AdminUtil.(Я добавил @PrepareForTest ({SystemSettings.class, AdminUtil.class}) поверх тестового класса)

PowerMockito.mockStatic(SystemSettings.getInstance().getClass());
        PowerMockito.doReturn(systemSettings).when(SystemSettings.class, "getInstance");
        PowerMockito.mockStatic(AdminUtil.class);
        PowerMockito.doReturn(true).when(AdminUtil.class, "isEnterpriseVersion");

Его выброс ниже исключения ...

    org.mockito.exceptions.misusing.UnfinishedStubbingException: 
    Unfinished stubbing detected here:
    -> at org.powermock.api.mockito.internal.PowerMockitoCore.doAnswer(PowerMockitoCore.java:36)

E.g. thenReturn() may be missing.
Examples of correct stubbing:
    when(mock.isOk()).thenReturn(true);
    when(mock.isOk()).thenThrow(exception);
    doThrow(exception).when(mock).someVoidMethod();
Hints:
 1. missing thenReturn()
 2. you are trying to stub a final method, you naughty developer!

1 Ответ

0 голосов
/ 10 октября 2018

Звонок на

PowerMockito.mockStatic(SystemSettings.getInstance().getClass())

вызывает фактический статический член.

Вам нужно изменить порядок расположения насмешек

boolean expected = true;
//create mock instance
SystemSettings settings = PowerMockito.mock(SystemSettings.class);    
//setup expectation
Mockito.when(settings.isEnterpriseVersion()).thenReturn(expected);

//mock all the static methods
PowerMockito.mockStatic(SystemSettings.class);
//mock static member
Mockito.when(SystemSettings.getInstance()).thenReturn(settings);

Так что теперьвызов

boolean actual = AdminUtil.isEnterpriseVersion();

должен вернуть true.

Ссылка Статический метод насмешки

...