0

Trying assertJ-swing for UI testing of java-swing based application.

Situation: Sample application in JavaApp.java (with Main class) works fine when it is invoked from this java file (running it as Java application). But when it is invoked from TestNG with assertj-swing's command:

application(JavaApp.class).start(); 

the application opens up but closes down immediately.

Question: Is it the only approach? Please suggest resolution or any other approach to launch the application and keep it open so further operations can be performed.

JavaApp:

package jdialogdemo;

import java.awt.*;
import java.awt.event.*;

import javax.lang.model.util.SimpleElementVisitor6;
import javax.swing.*;

public class JavaApp {
    public static void main(String[] args) throws Exception {
        final JFrame frame = new JFrame("JDialog Demo");
        final JButton btnLogin = new JButton("Click to login");

        btnLogin.addActionListener(
                new ActionListener(){
                    public void actionPerformed(ActionEvent e) {
                        LoginDialog loginDlg = new LoginDialog(frame);
                        loginDlg.setVisible(true);
                        // if logon successfully
                        if(loginDlg.isSucceeded()){
                            btnLogin.setText("Hi " + loginDlg.getUsername() + "!");
                        }
                    }
                });

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(700, 200);
        frame.setLocationRelativeTo(null);
        frame.setLayout(new FlowLayout());
        frame.getContentPane().add(btnLogin);
        frame.setVisible(true);
     }
}
Atul K
  • 1
  • 2

1 Answers1

0

AssertJ-Swing verifies that you only do access swing components on the EDT (as required because Swing is not thread safe, see Concurrency in Swing - Initial threads).

Your main method violates this (by constructing the UI from the main thread) and therefore AssertJ-Swing fails with an exception.

To correct the problem your main method should look like this:

public class JavaApp {
    public static void main(String[] args) throws Exception {
        SwingUtilities.invokeLater(() -> {
            final JFrame frame = new JFrame("JDialog Demo");
            final JButton btnLogin = new JButton("Click to login");
//...
        });
    }
}
Thomas Kläger
  • 17,754
  • 3
  • 23
  • 34