3
\$\begingroup\$

I have a Java/Swing/Guice application that uses multiple frames. When the application runs normally, I just want some of these frames to hide (and the "master" frame can unhide them).

When testing the view, I have various other main methods that can open just one frame, and perhaps populate them with sample data. However, then the test application has no way to close (because their normal operation is to be hidden). But, I don't want to mess around with the constructor because I don't want this testing functionality to affect appear anywhere else, I want the "normal operation" module to have no knowledge of this behavior, because it's for testing, only.

Note: this is View testing (like, does it look the way I want it to?), so it's not really appropriate for JUnit.

How is this solution? Is there a better one?

public class SubView {
    private JFrame frame;
    public SubView() {
        initialize();
    }
    private void initialize() {
        frame = new JFrame();
        // etc. note, I don't call frame.setDefaultCloseOperation
        // here, as hide is what I want
    }
    @Inject
    private void setCloser(Closer c) {
        frame.setDefaultCloseOperation(c.closeOperation);
    }
    private static class Closer {
        @Inject(optional=true) @Named("closeOperation")
        private int closeOperation = WindowConstants.HIDE_ON_CLOSE;
    }  
}

And then in my test class:

public SubViewTester {
    public static void main(String... args) {
        Module testSpecific = new AbstractModule() {
            @Override
            protected void configure() {
                bindConstant().annotatedWith(Names.named("closeOperation"))
                        .to(WindowConstants.EXIT_ON_CLOSE);
            }
        };
        Injector inj = Guice.createInjector(/* maybeSomeOtherModule, */ testSpecific);
        SubView view = inj.getInstance(SubView.class);
        EventQueue.invokeLater(new Runnable() {
            view.setVisible(true);
        }
    }
}
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

The Closer class and its setCloser method does not close anything so I'd rather call it CloseOperationProvider. I guess you could get rid of it and annotate the setCloser() parameter instead:

@Inject(optional = true)
private void setCloseOperation(@Named("closeOperation") int closeOperation) {
    frame.setDefaultCloseOperation(closeOperation);
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.