Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 869697
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T10:21:03+00:00 2026-05-15T10:21:03+00:00

Consider this code: public void actionPerformed(ActionEvent e) { setEnabled(false); new SwingWorker<File, Void>() { private

  • 0

Consider this code:

public void actionPerformed(ActionEvent e) {
    setEnabled(false);
    new SwingWorker<File, Void>() {

        private String location = url.getText();

        @Override
        protected File doInBackground() throws Exception {
            File file = new File("out.txt");
            Writer writer = null;
            try {
                writer = new FileWriter(file);
                creator.write(location, writer);
            } finally {
                if (writer != null) {
                    writer.close();
                }
            }
            return file;
        }

        @Override
        protected void done() {
            setEnabled(true);
            try {
                File file = get();
                JOptionPane.showMessageDialog(FileInputFrame.this,
                    "File has been retrieved and saved to:\n"
                    + file.getAbsolutePath());
                Desktop.getDesktop().open(file);
            } catch (InterruptedException ex) {
                logger.log(Level.INFO, "Thread interupted, process aborting.", ex);
                Thread.currentThread().interrupt();
            } catch (ExecutionException ex) {
                Throwable cause = ex.getCause() == null ? ex : ex.getCause();
                logger.log(Level.SEVERE, "An exception occurred that was "
                    + "not supposed to happen.", cause);
                JOptionPane.showMessageDialog(FileInputFrame.this, "Error: "
                    + cause.getClass().getSimpleName() + " "
                    + cause.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
            } catch (IOException ex) {
                logger.log(Level.INFO, "Unable to open file for viewing.", ex);
            }
        }
    }.execute();

url is a JTextField and ‘creator’ is an injected interface for writing the file (so that part is under test). The location where the file is written is hard coded on purpose because this is intended as an example. And java.util.logging is used simply to avoid an external dependency.

How would you chunk this up to make it unit-testable (including abandoning SwingWorker if needed, but then replacing its functionality, at least as used here).

The way I look at it, the doInBackground is basically alright. The fundamental mechanics are creating a writer and closing it, which is almost too simple to test and the real work is under test. However, the done method is quote problematic, including its coupling with the actionPerformed method the parent class and coordinating the enabling and disabling of the button.

However, pulling that apart is not obvious. Injecting some kind of SwingWorkerFactory makes capturing the GUI fields a lot harder to maintain (it is hard to see how it would be a design improvement). The JOpitonPane and the Desktop have all the “goodness” of Singletons, and exception handling makes it impossible to wrap the get easily.

So what would be a good solution to bring this code under test?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T10:21:03+00:00Added an answer on May 15, 2026 at 10:21 am

    IMHO, that’s complicated for an anonymous class. My approach would be to refactor the anonymous class to something like this:

    public class FileWriterWorker extends SwingWorker<File, Void> {
        private final String location;
        private final Response target;
        private final Object creator;
    
        public FileWriterWorker(Object creator, String location, Response target) {
            this.creator = creator;
            this.location = location;
            this.target = target;
        }
    
        @Override
        protected File doInBackground() throws Exception {
            File file = new File("out.txt");
            Writer writer = null;
            try {
                writer = new FileWriter(file);
                creator.write(location, writer);
            }
            finally {
                if (writer != null) {
                    writer.close();
                }
            }
            return file;
        }
    
        @Override
        protected void done() {
            try {
                File file = get();
                target.success(file);
            }
            catch (InterruptedException ex) {
                target.failure(new BackgroundException(ex));
            }
            catch (ExecutionException ex) {
                target.failure(new BackgroundException(ex));
            }
        }
    
        public interface Response {
            void success(File f);
            void failure(BackgroundException ex);
        }
    
        public class BackgroundException extends Exception {
            public BackgroundException(Throwable cause) {
                super(cause);
            }
        }
    }
    

    That allows the file writing functionality to be tested independent of a GUI

    Then, the actionPerformed becomes something like this:

    public void actionPerformed(ActionEvent e) {
        setEnabled(false);
        Object creator;
        new FileWriterWorker(creator, url.getText(), new FileWriterWorker.Response() {
            @Override
            public void failure(FileWriterWorker.BackgroundException ex) {
                setEnabled(true);
                Throwable bgCause = ex.getCause();
                if (bgCause instanceof InterruptedException) {
                    logger.log(Level.INFO, "Thread interupted, process aborting.", bgCause);
                    Thread.currentThread().interrupt();
                }
                else if (cause instanceof ExecutionException) {
                    Throwable cause = bgCause.getCause() == null ? bgCause : bgCause.getCause();
                    logger.log(Level.SEVERE, "An exception occurred that was "
                        + "not supposed to happen.", cause);
                    JOptionPane.showMessageDialog(FileInputFrame.this, "Error: "
                        + cause.getClass().getSimpleName() + " "
                        + cause.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                }
            }
    
            @Override
            public void success(File f) {
                setEnabled(true);
                JOptionPane.showMessageDialog(FileInputFrame.this,
                    "File has been retrieved and saved to:\n"
                    + file.getAbsolutePath());
                try {
                    Desktop.getDesktop().open(file);
                }
                catch (IOException iOException) {
                    logger.log(Level.INFO, "Unable to open file for viewing.", ex);
                }
            }
        }).execute();
    }
    

    Additionally, the instance of FileWriterWorker.Response can be assigned to a variable and tested independent of FileWriterWorker.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 427k
  • Answers 427k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer git rm --cached dirToignore echo dirToignore >>.gitignore From there, a… May 15, 2026 at 1:06 pm
  • Editorial Team
    Editorial Team added an answer Instead of $.get() you should use .load(), like this: $('#sortable').load('incl/ajax_category.php?action=filtercat',… May 15, 2026 at 1:06 pm
  • Editorial Team
    Editorial Team added an answer Heroku's docs say to use Tempfile. Well, it says in… May 15, 2026 at 1:06 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.