Test methods inside UI class without UI creation - java

On my personal proyect, I want to make unit-tests but I'm having troubles with that.
My project does not have a big logic layer. The most important logic is the interaction between UI and entities. Some exception are calculate some day from payments and others things. Those things rarely change and, I want to start with things that change frecuently.
For example, please look this class:
public class TabClient extends JPanel{
private JDateChooser dateChooser = ...
private JButton update = ...
private JButton search = ...
private JButton delete = ...
//other components specific for this panel/component
private SomeOtherClassComponent subComponent = ...
private void initComponents()
{
update.addActionListener(ClientHandler.getUpdateListener());
//Others buttons
}
protected void mapFrom(Entitie entitie){
subComponent.mapFrom(entitie);
dateChooser.setDate(entitie.getDateFor...());
//specific components mappings
}
protected void mapTo(Entitie entitie){
subComponent.mapTo(entitie);
entitie.setDateFor...(dateChooser.getDate());
//specific components mappings
}
}
This class is an example of a Tab (TabbedPane item) from my project.
The class ClientHandler is like a Mediator pattern who creates (and returns) EventListener to encapsulate the UI events. Some events call methos from Tab component like mapFrom
I want to write tests for the methods but I don't know where to start. If test with UI frameworks or refactor clasess to separate some things (what to separate? and where?) or what to do to start with unit-tests.
Nowdays, the test is made by hand using the app.
What I have to do to start with unit tests?
What I should test? Methods that interact with UI or what?

In order to have an (easily) testable class, they need to have a high degree of cohesion, which may not be your case
You may want to consider moving any business logic to specific services or to the domain layer so that you can more easily test them.
As you mentioned the most import part of your application is the UI, I would try to mock the TabClient dependencies, simulate (say) the press of a button by calling its action methods and then checking the mocked objects to make sure the appropriate flow was invoked (ie, assert the right methods of the right objects were called). You may need to refactor your classes a bit to make possible to mock their dependencies. Likewise, I would write tests for all relevant UI objects.
I have never tested Swing applications to be honest, nevertheless I found the following links that might shed some light on your question (though some of them might require UI creation):
UISpec4J
Java World
Stack Overflow

Related

Which design pattern can I use to supply several methods that create "pre-configured" UI components

Disclaimer: I’m new to programming in Java and working with “extreme” OOP in general, so the answer to this might be really simple.
I’m creating a user interface in Vaadin, a Web application framework that supplies lots of useful components for me. Often, I’m not entirely happy with the default settings for these components.
For example, if I want every TextField component to fire value change events immediately when the field loses focus. There are similar settings for UploadField, TextArea, ComboBox etc. that I want to set on every instance of those classes.
Currently, what I have looks like this:
public class ConfiguredComponents {
public static TextField createConfiguredTextField(String caption) {
TextField field = new TextField(caption);
field.setImmediate(true);
field.setSomeOtherOptions();
...
return field;
}
public static UploadField createConfiguredUploadField(...) {
...
}
// etc.
}
This doesn’t feel like a class at all! It’s just a collection of static methods, which I’ve been told to avoid. Plus, I would like to place the logic for each component in a separate file. The configuration gets quite involved sometimes, and it just makes more sense that way: these are all very tiny self-contained bits of logic.
Here are the solutions I’ve considered:
Keep it simple: I could get rid of ConfiguredComponents, and just make one big package containing small factory classes. For example, myproject.ui.components.TextFieldFactory knows how to create a configured TextField and nothing more.
Pros:
The ugly ConfiguredComponents class is gone.
All of the logic is in separate files.
Cons:
There’s no single interface to the creation of my configured components; the only thing keeping them together is the fact that they’re in the same directory. Basically, I have to expose a lot of tiny classes, and there’s no single class or object managing them. (This intuitively feels like a pretty bad thing, but I don’t know if it really is.)
There’s also no way to override or extend static methods, so “faking” UI stuff for testing gets harder.
The Abstract Factory pattern: I make ConfiguredComponents into an AbstractComponentFactory that manages a lot of smaller factories.
Pros:
All of the logic is in separate files.
The logic that actually configures my components is fully behind-the-scenes.
Cons:
I would need an instance of AbstractComponentFactory every time I want to create a component anywhere in the code for my views. This means either keeping a singleton object, which has a lot of downsides, or creating a new AbstractComponentFactory() every time.
I have to write new code in two or three places, instead of just one, if I wish to add new components to my little “library”.
Some other design pattern I don't know about: I’ve read a bit about Builder, and Facade, which feel like they might apply here, but I don’t understand them very well.
How would you approach this design decision?
If your components can be inherited, then go ahead; for each component that you want to alter default settings, create a new derived class and config settings in constructors. Otherwise,
Abstract factory pattern is a good choice. I think you are misunderstanding about this pattern. AbstractComponentFactory is just an interface, it does not manage anything. This interface looks like this:
interface AbstractComponentFactory {
public TextField createTextFiled(...);
public UploadField createUploadFiled(...);
...
}
In your situation, I think you need only one implementation for this factory:
class MaurisComponentFactory implements AbstractComponentFactory {
public TextField createTextFiled(...) {
new ... config ... return;
}
public UploadField createUploadFiled(...) {
new ... config ... return;
}
...
}
As you said, we should neither use Singleton nor create new MaurisComponentFactory everytime. Instead, we should create only one instance in the main() method, and then try to inject this instance to every place that need to create components.
One possible approach i can think think is to use AbrstractFactory with Service Locator or Registry patterns
Since you have myriad objects that does not have complicated instantiation process (if so resort to build pattern), you create objects with Abstract Factory and register them in registry. And resolve them as needed where ever you are.
or you may resort simple IOC container where your entire application is wrapped around

Java Swing GUI User actions handling

How should Listeners etc be managed? I've found only examples with one button etc.
I can think of following options:
Extra class for each - doesn't seem right, especially when items
can be created dynamically
Class for each group (such as form1,
form2, controlButtonsOnLeft, controButtonsOnRight, mainMenu,
userMenu, ...) where I'll check which button/component caused this
(via getSource method for example)
Some super (sized) controller,
which will accept all user actions
New anonymous class for each,
which will call controller's method with parameters specifying
details (probably enums)
And another question: I've found many examples for MVC, I was wondering what is better (or commonly used) for app. developed by 1 person (app will not be huge)?
A. Viewer sets listeners to controller (A1-3)
B. Controller calls viewer's methods, which accepts listener as parameter (methods addLoginSubmitListener, addControlBoldButtonListener etc)
All of above are possible to implement and so far I would choose B4.
Meaning in Control I would do something like this:
...
viewer.addLoginButtonListener(new Listener()
{
#Override
public void actionPerformed(ActionEvent e) {
...
someButtonsActionHandler(SomeButtonEnum, ActionEnum);
...
}
});
...
private void LoginActionHandler(LoginElementsEnum elem, ActionEnum action)
{
if (elem.equals(LOGINBUTTON)) {...}
...
}
...
This combines readable code (1 logic part at one place in code), doesnt create any unwanted redundant code, doesnt require any hardly-dynamic checks, is easily reusable and more.
Can you confirm/comment this solution?
To be honest the question comes down to a number of questions...
Do you want reusability?
Do you want configurability?
Are they self contained? That is, does it make sense for anybody else to listener to the component or need to modify the resulting action of the listener in the future?
Personally, I lean towards self containment. A single listener for a given action/task. This makes it easier to manage and change should I need to.
If I don't need reusability (of the listener) or configurability, then an anonymous inner class is generally a preferred choice. It hides the functionality and doesn't clutter the source code with small, once use classes. You should beware that it can make the source code difficult to read though. This of course assumes that the task is purpose built (its a single, isolated case). Normally, in these cases I will prefer to call other methods from the listener that actually do the work, this allows a certain amount of flexibility and extendability to the class. Too often you find yourself wanting to modify the behaviour of a component only to find that behaviour buried within an anonymous or private inner class...
If you want reusability and/or configurability - that is, the listener performs a common task which can be repeated throughout the program or over time via libraries, then you will need to provide dedicated classes for the task. Again, I'd favour a self contained solution, so any one listener does only one job, much easier to change a single listener then having to dig through a compound list of if-else statements :P
This could also be a series of abstract listeners, which can build functionality for like operations, deleting rows from a table for example...
You could considering something like the Action API (see How to Use Actions for more details), which are self contained units of work but which also carry configuration information with them. They are designed to work with buttons, such as JButtons and JMenuItems, but can also be used with key bindings, making them extremely versatile...
The second part of you question (about MVC) depends. I prefer to keep UI related functionality in the view and out of the controller as much as possible. Instead of allowing the controller to set listeners directly to components, I prefer to provide my own, dedicated, listener for the controller/view interaction, which notifies the controller of changes to the view that it might like to know about and visa versa.
Think about it this way. You might have a login controller and view, but the controller only cares about getting the credentials from the view and authenticating them when the view makes the request, it doesn't care how that request is made from the views perspective. This allows you to design different views for different circumstances, but so long as you maintain the contract between the view and the controller, it won't make any difference...But that's just me.

Organize Code for GUI and ActionListener in Java [duplicate]

This question already has answers here:
Implement an interface and override methods in Java?
(6 answers)
Closed 4 years ago.
I am new to Java and was wondering how I would go about implementing ActionListener code in my project. I am aware of inner classes and the implementation the ActionListener interface, but going down that road makes the code look more messy than it probably should.
Would I write another class ActionCode that implements ActionListener and extends GUI or what road would you suggest and why?
What's your best practice advise on that and where can I find those guidelines?
(The JavaDoc seems to explain the basic implementation of ActionListeners, but doesn't seem to have any model how to organize large/medium projects).
In my opinion, there is no "best" approach. Even the code examples from sun/oracle tutorials use different ways to implement listeners.
From my experience, a good approach is:
Use anonymous implementations: People know this pattern and will quickly recognize it. It helps the reader to understand the code if there is a common way to do things
Have a special method, which only handles the listeners (e.g. private void addListeners()): Again, this helps everyone to recognize it and to know where to search for all the logic
Keep the listeners simple. This means less than 5-10 lines of code. If you need more complex logic, call a method.
Keep the number of listeners small. If you need > 50 listeners, you should probably refactor your view. If you need more than 10, you could think about refactoring.
Beside this general points, there are always exceptions. Like if you have a lot of Components with the same behavior, you could write a generic listener with a switch/case. (Typical example: buttons from a calculator or menu buttons).
Or if you have the same logic for multiple components, you could use a specific class.
And so on.
And just to mention it, because there are some examples in the sun/oracle tutorials: Try to avoid implementing a listener interface with the view class itself. This could be ok if you have only one listener, but it is most of the times awful for multiple events from multiple source with different behavior.
Code style can be a matter of personal taste, but modern literature suggests it's more than that. Let the chapter on Classes in Clean Code show you the way.
Classes Should Be Small!
The first rule of classes is that they should be small. The second rule
of classes is that they should be smaller than that. No, we’re not
going to repeat the exact same text from the Functions chapter. But as
with functions, smaller is the primary rule when it comes to designing
classes. As with functions, our immediate question is always “How
small?” With functions we measured size by counting physical lines.
With classes we use a different measure. We count responsibilities...
The Single Responsibility Principle (SRP) states that a class or
module should have one, and only one, reason to change. This principle
gives us both a definition of responsibility, and a guidelines for
class size. Classes should have one responsibility—one reason to
change...
The problem is that too many of us think that we are done once the
program works. We fail to switch to the other concern of organization
and cleanliness. We move on to the next problem rather than going back
and breaking the overstuffed classes into decoupled units with single
responsibilities. At the same time, many developers fear that a large
number of small, single-purpose classes makes it more difficult to
understand the bigger picture. They are concerned that they must
navigate from class to class in order to figure out how a larger piece
of work gets accomplished. However, a system with many small classes
has no more moving parts than a system with a few large classes. There
is just as much to learn in the system with a few large classes. So
the question is: Do you want your tools organized into toolboxes with
many small drawers each containing well-defined and well-labeled
components? Or do you want a few drawers that you just toss everything
into?
Every sizable system will contain a large amount of logic and
complexity. The primary goal in managing such complexity is to
organize it so that a developer knows where to look to find things and
need only understand the directly affected complexity at any given
time. In contrast, a system with larger, multipurpose classes always
hampers us by insisting we wade through lots of things we don’t need
to know right now. To restate the former points for emphasis: We want
our systems to be composed of many small classes, not a few large
ones. Each small class encapsulates a single responsibility, has a
single reason to change, and collaborates with a few others to achieve
the desired system behaviors.
So, based on these heuristics, Nested Classes break SRP. They should almost never happen. Instead, have your GUI classes include instance members of the ActionListeners they register. Keep the listeners in a separate *.listener package. Use interfaces to make them replaceable (Strategy Pattern) wherever deemed effective.
Java and Swing encourage lots of little objects like Listeners and Actions. It's a lot of boiler-plate, but that's the way Java is. There's little benefit in fighting it.
Creating anonymous listeners inline is fairly painless:
JButton okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ok();
}
});
But, you often need to reuse actions, say to assign the same action to a menu and a button. You might put them in your main application window as inner classes:
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class MainWindow extends JFrame {
ZapAction zapAction;
public MainWindow() {
setSize(new Dimension(200,200));
zapAction = new ZapAction();
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Foo");
menu.add(new JMenuItem(zapAction));
menuBar.add(menu);
setJMenuBar(menuBar);
JButton zapButton = new JButton(zapAction);
add(zapButton);
}
public void zap() {
// do some zapping
System.out.println("Zap!");
// maybe we're all done zapping?
zapAction.setEnabled(isZappingPossible());
}
public boolean isZappingPossible() {
// determine if there's zapping to be done
return Math.random() < 0.9;
}
class ZapAction extends AbstractAction {
public ZapAction() {
super("Zap");
putValue(AbstractAction.SHORT_DESCRIPTION, "Zap something");
putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(
KeyEvent.VK_Z, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
putValue(AbstractAction.SMALL_ICON,
new ImageIcon(MainWindow.class.getResource("/icons/zap.png")));
setEnabled(true);
}
public void actionPerformed(ActionEvent e) {
zap();
}
}
}
public class Zap {
public static void main(String[] args) {
MainWindow mainWindow = new MainWindow();
mainWindow.setVisible(true);
}
}
Here, ZapAction is package-private visibility. I put all the UI code in it's own package (say org.myorg.myproject.ui). So, all the UI objects have access to the actions.
In a complex swing app, I've gone as far as to create a UI facade layer, which makes a nice place for the actions and all the code that wires them up to various controls. It also makes a convenient place for external code to interact with the UI, keeping UI code isolated from core application code.

define button actions in inner class Vs define button actions in public class in swing

I have a dialog, which have four buttons say New, Save, Delete, Cancel. Now each of these need to perform their action. So I have defined a separate class which implements an ActionListener. I have used this class to perform each of the button action.
public class MyClass implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().toString() == "OK") {
// Code
} else if( .. ){
}
}
}
What I have done is, I defined an inner class which I used to do the same functionality. But what I was not getting is, is it best practice to write a separate class or is it best to use inner class. I was suggested to write in a public class so tomorrow some one can use this class to perform their action. So I have the following questions,
If the functionality is not called by any object (which I can't say) then I can write it in inner class? OR
Is it a good practice always to write inner class which performs the actions of that dialog?
There is no general answer to these questions. If the code in actionPerformed() is one line, writing a whole class file is usually overkill.
If the code is more complex, it might be suitable to reuse but as the code grows, it also gets more specific (so you can't reuse it anymore).
Try to follow this approach:
Build your application from simple blocks that are independent of each other.
Configure the application by writing code that connects the blocks.
So in your case, you could have helper methods which do the work. Wrap them in Swing Actions; this allows you to use them in all kinds of buttons and menus.
Try to move as much work as possible into the helpers so that the actions become really simple. If in doubt, ask yourself: Is this code part of the work? Does everyone need to do this?
If yes, then the code should go into a work/helper class.
If it's things like UI related checks (visible/enabled), conversion (string to number), validation, etc., it should go into the action.
When you talk about defining an inner class for a GUI listener, I think immediately of using anonymous classes to do the job:
newButton.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
// do the work for a button press
}
});
// similarly for save, cancel, delete buttons:
saveButton.addActionListener(
new ActionListener()
{
// ...
You'll often see this, and I often use this in my own code.
Which you use depends on the structure of your code, for instance:
how much work each listener needs to do
how much code is shared between the handlers
If each handler is short (e.g. just one method call, with all the real work handled within another class method), I'll use anonymous classes this way. But it does look goofy: unfortunately java requires us to define an object to employ a callback method.
It's also a matter of personal preference and coding style.
However, I'd rarely make a new top-level class for a GUI handler as in your example: even if I separate out the class so that I use the same class for each button, I'd define the class within the class file controlling the buttons, either as a non-public top-level class, or as an inner (non-anonymous) class. If the complexity of a GUI callback grows to the point that it deserves a separate class, I'd start looking for places to refactor.
proper way should be Swing Action(mentioned in comment by #Robin), for JButtons Components as most scalable choice, with implementations of interesting methods
most complex GUI is there way to add EventHandler, which fired event and could be compare in String value

Best way to separate Business from Presentation Logic?

I want to create a game that will work both locally and online.
My first thought was to create an interface that would have all the methods that will be needed by the GUI for the business logic and then have a network implementation and a local implementation.
This works fine for request-response messages. But what about messages that the server sends, where I have to update some GUI components (i.e. JLabels)?
My first solution to this was to implement listeners, where each change in the implementation will fire an event. The GUI would register and change it's components appropriately. However, calls to fire events in the business logic looks a little wrong.
Am I in the right track? Because I think I'm not. Any suggestions?
Thank you.
NOTE: The client is a simple Java Swing GUI.
What you have described will serve the goal of keeping the model independent of presentation issues, which is A Good Thing. This will also help you during design, development, and maintenance of the model, because you can write unit tests on the basis that certain changes in the model should fire specific events, without worrying about what that might look like on a screen.
And, of course, it frees you up to have different GUI designs for different environments.
The key is that the events should be about changes in the state of the model, and not about intended actions/representations at the presentation level. Let the presentation layer deal with whether/how to respond to a model event.
I'll admit that I do web development, so I don't have much experience with Swing.
But I've always thought that the way I'd approach it would be to break the app into packages /view, /model, and /controller. The relationships would be unidirectional: /controller would know about both /model and /view, but neither would import any classes from /controller or each other.
The /view layer components would never be JFrames; they'd always be JPanel or another suitable container that could be composed together into JFrames as needed. Each would have references to Listener interfaces, initialized in constructors, and would defer to these for event handling:
public class ExamplePanel extends JPanel implements ActionListener
{
private JButton button;
private ActionListener buttonListener;
public ExamplePanel(ActionListener buttonListener)
{
this.button = new JButton("Do Something");
this.buttonListener = buttonListener;
this.button.addListener(this.buttonListener);
}
public void actionPerformed(ActionEvent e)
{
this.buttonListener.actionPerformed(e);
}
}
This arrangement works well with dependency injection, because now the controller can choose to use a local or remote implementation of that Listener interface, changing the behavior in a way that doesn't affect the client at all.
I'll admit that I've never followed it all the way through.
The Spring folks have a rich Swing client module, but it appears to have fallen out of favor. It looks like they've decided that a BlazeDS direction is a better choice for rich clients. But perhaps you can glean some design ideas from their approach.

Categories