HowTo: testing jFace Action class taking a StructuredSelection object
2 min read
2 min read
public class RateAction extends Action {Action classes are heavily used in the Eclipse plugin development environment. They are basically nothing other than the representation of the Command design pattern, which is an extremely useful pattern. For instance for factoring out/grouping common behavior. Do not always put it in a common superclass: inheritance should only be used for specialization and moreover it imposes a very strong dependency among the classes. Command objects can be easily exchanged and are much lower coupled.
private final int fRating;
private IStructuredSelection fSelection;
/**
* @param rating
* @param selection
*/
public RateAction(int rating, IStructuredSelection selection) {
//hack: have to use a button because otherwise the star images won't show up on Linux (Ubuntu)
super("", AS_PUSH_BUTTON);
fRating = rating;
fSelection = selection;
setImageDescriptor(createImageDescriptor());
}
...
/*
* @see org.eclipse.jface.action.Action#run()
*/
@Override
public void run() {
List<INews> newsList = ModelUtils.getEntities(fSelection, INews.class);
if (newsList.isEmpty())
return;
/* For each News */
for (INews newsItem : newsList) {
newsItem.setRating(fRating);
}
/* Save */
DynamicDAO.saveAll(newsList);
}
}
public class RateActionTest {
private RateAction action = null;
private INews newsItem = null;
private IStructuredSelection selection = null;
@Before
public void setUp() throws Exception {
//reset DB schema
Owl.getPersistenceService().recreateSchema();
//construct the necessary selection
IFeed feed = new Feed(Long.parseLong("" + 0), new URI("http://www.dummyurl.com"));
newsItem = new News(feed);
selection = new StructuredSelection(newsItem);
}
@After
public void tearDown() throws Exception {
selection = null;
newsItem = null;
action = null;
}
/**
* Tests the actions core parts
*/
@Test
public void testAction(){
assertNotNull(newsItem);
//Verify that the created newsItem has a rating of 0
assertEquals("rating should be equal to 0", 0, newsItem.getRating());
//boundary test: empty selection -> nothing should happen, no exception etc..
action = new RateAction(3, new StructuredSelection());
action.run();
//start the Action and set some rating
action = new RateAction(3, selection);
action.run();
assertEquals("rating should be equal to 3", 3, newsItem.getRating());
//decrease the rating again
action = new RateAction(1, selection);
action.run();
assertEquals("rating should be equal to 1", 1, newsItem.getRating());
}
}