Skarsh
Skarsh

Reputation: 63

Internal graphics not initialized yet in JUunit test case

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());
    }
}

Upvotes: 2

Views: 5573

Answers (1)

AlmasB
AlmasB

Reputation: 3407

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

Upvotes: 6

Related Questions