为什么在模拟中调用javafx Alert showAndWait?

时间:2018-08-25 22:27:53

标签: javafx mockito

我想测试Alert showAndWait()方法是否被调用。我用Mockito模拟Alert并验证是否调用了showAndWait()。但是问题是Alert.showAndWait()实际上被调用,而不是模拟方法被调用。我认为这不应该发生。

我的代码:

package drakonli.jcomponents.notificator;

import javafx.scene.control.Alert;
import junit_util.JavaFXThreadingRule;
import org.junit.Rule;
import org.junit.Test;

import static org.mockito.Mockito.mock;

    public class AlertTest
    {
        @Rule public JavaFXThreadingRule javafxRule = new JavaFXThreadingRule();

        @Test
        public void success()
        {
            Alert alert = mock(Alert.class);

            alert.showAndWait();

            verify(alert, atLeastOnce()).showAndWait();
        }
    }

例外:

java.lang.NullPointerException
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.control.Dialog.showAndWait(Dialog.java:331)
    at drakonli.jcomponents.notificator.AlertNotificatorTest.success(AlertNotificatorTest.java:30)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at junit_util.JavaFXThreadingRule$OnJFXThreadStatement$1.run(JavaFXThreadingRule.java:65)
    at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
    at java.lang.Thread.run(Thread.java:748)

1 个答案:

答案 0 :(得分:1)

Mockito无法模拟Final方法或类。 Powermock可以,但是我不建议使用任何新功能(它被过度使用或使用不当)。我建议您为框架寻找测试工具,或者解决一些局限性,并接受一些不能被有效测试的东西。