Internal graphics not initialized yet in JUunit test case

蹲街弑〆低调 提交于 2020-12-14 05:01:10

问题


I'm making a light weight painting application with JavaFx. I've been having some issues with my LayerController class and it's methods addLayer etc. So I thought that writing some JUunit test cases would be a good idea to check the correctness of my methods. To make the story short, I'm painting on a Canvas using its GraphicsContext in a selfmade class which I call PaintGraphics. This class does all the painting. The LayerController needs a PaintGraphics to do its work on the layers. But it seems something goes wrong when I initiate a GraphicsContext in a test case. I get the error "Internal graphics not initialized yet.". Which I guess has something to do with the GraphicsContext but I'm not sure. Any ideas about why the error occurs, and how to solve it would be much appreciated!

The source code for the test looks like this:

package view;

import static org.junit.Assert.*;

import java.util.ArrayList;

import org.junit.Test;

import controller.LayerController;
import javafx.scene.canvas.Canvas;
import javafx.scene.layout.AnchorPane;
import model.Layer;
import model.PaintGraphics;

public class LayoutControllerTest {

    Layer layer = new Layer(0, new Canvas(100,100));
    ArrayList<Layer> layers = new ArrayList<Layer>();
    PaintGraphics pGraphics = new PaintGraphics(layer.getCanvas().getGraphicsContext2D());
    LayerController layerController; 

    @Test
    public void addLayerTest() {
        layers.add(layer);
        layerController.addLayer(layer, (AnchorPane)layer.getCanvas().getParent());
    }
}

回答1:


The exception "Internal graphics not initialized yet." is typically thrown when JavaFX requires the JavaFX platform to be initialized first before using certain features, e.g. Canvas. Approaches to solving this are listed below:

  1. Make a tiny mock application class that extends Application and launch it in a background thread, so the JavaFX Application thread can properly initialize, while you don't block your testing thread.
  2. Use JavaFX testing library, e.g. TestFX
  3. You might be able to mock the canvas object using Mockito


来源:https://stackoverflow.com/questions/39582837/internal-graphics-not-initialized-yet-in-juunit-test-case

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!