4

Are there any examples on how to test single Component or JComponent with AssertJ?

Getting started guide shows strange example to test entire application with main class, which is no granulated enough. I am expecting to test custom components first.

UPDATE

Suppose I have the following component:

package tests;

import javax.swing.*;
import java.awt.*;

public class JCustomPanel extends JPanel {
    @Override
    public void paint(Graphics g) {
        super.paint(g);
        g.setColor(Color.RED);
        g.fillRect(0, 0, getWidth(), getHeight());
    }
}

and I wish to check if it appears red. What to write?

package tests;

import org.assertj.swing.edt.FailOnThreadViolationRepaintManager;
import org.assertj.swing.fixture.JPanelFixture;
import org.assertj.swing.testing.AssertJSwingTestCaseTemplate;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class Test01 extends AssertJSwingTestCaseTemplate {

    private JPanelFixture panel;

    @BeforeClass
    public static void setUpOnce() {
        FailOnThreadViolationRepaintManager.install();
    }

    @Before
    public void setUp() {
        panel = new JPanelFixture(robot(), new JCustomPanel());
    }

    @Test
    public void testColorIsRed() {
        //what to write here?
    }
}
Suzan Cioc
  • 29,281
  • 63
  • 213
  • 385

2 Answers2

2

Note there's a mailing list where you might receive fast answers for that specific questions as there might be only few AssertJ Swing users out there.

There's a examples project that is not very big but should grow to be a good reference for new users about how to use AssertJ Swing.

Unfortunately the 'application' you're trying to test is one, AssertJ Swing does not aim for. As it just seems to contain color you don't have many options. AssertJ Swing is intended to be a functional testing tool rather than a precise pixel testing tool. Thus it doesn't really have good support for making pixel tests.

For color, JPanelFixture provides foreground() and background() to do something like:

panel.background().requireEqualTo(Color.RED);

But as said this is not the main purpose of the library.

Bertram Nudelbach
  • 1,783
  • 2
  • 15
  • 27
-2

I am using assertj-swing a lot, and thinking you cannot verify the custom painting with it. - the foreground() from any fixture actually is calling its component. So they don't help in your case.

The other option is log some paint messages into your custom paint component and verify the messages. it mightbe too ugly but works.

MartinsL
  • 1
  • 2