JUnit Testing for a simple facade - java

Trying to come up with a JUnit test for the following facade - I know this should be simple but I keep coming up blank. Any ideas to get me going in the right direction. It doesn't need to be complicated - I just need to get it done.
package business;
import domain.Items;
import services.exceptions.ItemNotFoundException;
import services.itemservice.IItemsService;
public class Itemmgr {
#SuppressWarnings("static-access")
public void store(Items item) {
Factory factory = Factory.getInstance(IItemsService.NAME);
IItemsService storeItem = (IItemsService)factory.getInstance(IItemsService.NAME);
storeItem.storeItem(item);
}
public void get(Items item) throws ClassNotFoundException, ItemNotFoundException {
Factory factory = Factory.getInstance(IItemsService.NAME);
#SuppressWarnings("static-access")
IItemsService getItem = (IItemsService)factory.getInstance(IItemsService.NAME);
try {
getItem.getItems("pens", 15, "red", "gel");
} catch (ClassNotFoundException | ItemNotFoundException e) {
e.printStackTrace();
System.out.println("Error - Class or Item Not Found");
}
}
}

As others have said, you could just write a unit test that first stores some Items, then in the same test, retrieve the Items and make sure that what you got back was "equivalent" to what you stored in the first place.
For instance (if I may venture a guess), it sounds to me like your Itemmgr class might be extended down the road to include volatile and persistent versions (maybe one version is in-RAM, maybe one is on-disk). Your test could go so far as to make sure that item1 == item2 returns true in the RAM-resident version, but item1 != item2 && item1.equals(item2) returns true in the persistent test to ensure that item2 was serialized or copied from somewhere and isn't just retrieving the original from a Map of some kind. Just some ideas.

Related

Verify whether a method parameter is used in the method body

I have an interface which looks like the following
interface Evaluator {
boolean requiresP2();
EvalResult evaluate(Param1 p1, Param2 p2, Param3 p3);
// some more methods
}
This interface is implemented by several classes. The parameter p2 of the evaluate method is used by some and not used by others. The method requiresP2 basically returns a boolean telling whether the evaluate method uses p2 or not.
Now, this questions may appear a little weird out of context but believe me, it makes sense in our use case. Plus, it would require a lot of time to refactor all the code to eliminate the need for the requiresP2 method so I would appreciate if we discuss solutions other than a top-to-bottom refactoring of the codebase.
The problem is that the return value of method requiresP2 is based on how the evaluate method is implemented. Therefore everyone must ensure that they update the requiresP2 method when they change the evaluate method.
I am looking for ways so that this can be enforced by the compiler/unit-tests/linters rather than leaving it to the developer's memory.
EDIT: I am still exploring the applicability of mocking frameworks to this problem.
I thought that I could reflection in unit tests to inspect evaluate's body in the unit test to check if it refers to p2 or not and then making sure it matches with the value returned by requiresP2 method but it seems that it is not possible to inspect method body using reflection.
I am looking for suggestions on how to do this. Any input is appreciated.
There is another option you did not mention: a Static Code Analysis tool.
You can use the SonarQube + SonarLint combination in order to get your desired enforcement:
Use the SonarQube server in order to create a new static code analysis rule, which will be based on the interface you are using and your unique use case.
Then install SonarLint on your IDE/IDEs (Eclipse and IntelliJ are both supported), and connect it to the SonarQube server.
This way the static code analysis scan will detect improper usage of your interface and indicate this with a visual marking in the IDE, on the relevant code lines (which is actually linting your code).
You can use ASM to check whether the parameter is used.
To add it to your project using e.g. Apache Ivy, you would add this to ivy.xml:
<dependency org="org.ow2.asm" name="asm" rev="6.1.1" />
Or do the equivalent for Maven, Gradle, etc. Then you can check on the parameter by:
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.util.concurrent.atomic.AtomicBoolean;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
// . . .
public static boolean usesP2(Evaluator evaluator) {
AtomicBoolean usesP2 = new AtomicBoolean(false);
String internalName = evaluator.getClass().getName().replace('.', '/');
String classFileResource = "/" + internalName + ".class";
ClassVisitor visitor = new ClassVisitor(Opcodes.ASM6) {
#Override
public MethodVisitor visitMethod(int access, String name,
String desc, String signature, String[] exceptions) {
if ("evaluate".equals(name)) {
return new MethodVisitor(Opcodes.ASM6) {
#Override
public void visitVarInsn(final int insn, final int slot) {
if (slot == 2) usesP2.set(true);
}
};
}
return super.visitMethod(access, name, desc, signature, exceptions);
}
};
try (InputStream is = Evaluator.class.getResourceAsStream(classFileResource)) {
ClassReader reader = new ClassReader(is);
reader.accept(visitor, 0);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return usesP2.get();
}
public static void assertCorrectlyDocumentsP2(Evaluator evaluator) {
boolean usesP2 = usesP2(evaluator);
if (usesP2 && !evaluator.requiresP2()) {
throw new AssertionError(evaluator.getClass().getName() +
" uses P2 without documenting it");
}
if (!usesP2 && evaluator.requiresP2()) {
throw new AssertionError(evaluator.getClass().getName() +
" says it uses P2 but does not");
}
}
Unit tests:
#Test
public void testFalsePositive() {
assertCorrectlyDocumentsP2(new FalsePositive());
}
#Test
public static void testFalseNegative() {
assertCorrectlyDocumentsP2(new FalseNegative());
}
(This supposes there are two bad Evaluators, FalsePositive and FalseNegative, one of which documents that it uses P2 but doesn't, and the other which doesn't document that it uses P2 even though it does, respectively.)
Note: In usesP2 we check for a variable instruction (an instruction which accesses a local variable) in slot 2 of the stack frame. The slots are numbered from 0, and the first one is this. P2 is in slots 2 only because Evaluator::evaluate is an instance method. If it were a static method, we would have to check if slot 1 were used in order to detect if parameter P2 were used. Caveat lector.

Java - Choosing the design pattern - 2 interfaces with same methods, except one has an extra parameter

So I have 2 interfaces (show below), 1 for regular/free kits and another one for purchasable kits. They both contain 2 methods, but in the "getIcon" method for purchasable kits, I need the player's profile as a parameter so I can check if they have bought the kit.
What is the best design pattern to use to link these 2 interfaces? and can you possibly show me the code to do it?
The 2 interfaces:
public interface Kits {
void giveKit(Player player);
Item getIcon();
}
public interface PurchasableKits {
void giveKit(Player player);
Item getIcon(Profile profile);
}
I attempted to use the adapter pattern but it doesn't seem right because the "getIcon" method is taking in a profile as a parameter but it doesn't get used.
public class KitAdapter implements PurchasableKits {
private Kits kits;
public KitAdapter(Kits kits) {
this.kits = kits;
}
#Override
public void givetKit(Player player){
kits.giveKit(player);
}
#Override
public void getIcon(Profile profile){
kits.getIcon();
}
}
Thanks in advance
You have 1 interface PurchasableKits. A free Kit would implement the interface and call getIcon(null).
The red flag is that the 2 interfaces are almost exactly the same. No design pattern will get you out of the situation that creates.
That's a tricky question because of the rules of the inheritance and cyclic inheritance avoided in java.
I don't believe that you need to interfaces, you could do something like this:
public interface Kits {
void giveKit(Player player);
//a vargars usage
Item getIcon(Profile... p);
}
public class ConcreteClass implements Kits{
#Override
public void giveKit(Player player) {
// TODO Auto-generated method stub
}
#Override
public Item getIcon(Profile... o) {
//This is the ugly thing of this method. You must check the sent params.
//However I think it is better than send a null param, as the clean code suggest to avoid
if(o.length == 0)
System.out.println("without profile");
else
System.out.println("With profile");
return null;
}
}
public class Main {
public static void main(String[] args) {
ConcreteClass my = new ConcreteClass();
my.getIcon();
my.getIcon(new Profile());
}
}
The output:
without profile
With profile
So I have 2 interfaces (show below), 1 for regular/free kits and another one for purchasable kits. They both contain 2 methods, but in the "getIcon" method for purchasable kits, I need the player's profile as a parameter so I can check if they have bought the kit.
Whether or not the profile is needed in the getIcon(...) method is an implementation detail of those Kits that are purchasable. I would just have a Kit interface that has the following definition:
public interface Kit {
void giveKit(Player player);
Item getIcon(Profile profile);
}
So every time you wanted to get the icon you would pass in the Profile and it would be up to the kits that are purchasable to look at the profile. The free ones would just ignore the argument. That you sometimes pass in null and sometimes not means that you know beforehand whether or not it is free which means that something is wrong with your model.
Couple of other comments about your code. Just my opinions:
Concrete classes tend to be nouns. Interfaces tend to be verbs. Maybe KitHandler instead of Kit?
Class names tend to be singular so then you can put them in a list. Maybe Kit (or KitHandler) would be better so you can create a List<Kit> kits = ....
I used get methods to return fields which means that they typically don't take arguments. Maybe getIcon should be generateIcon(...)?

Weka: Supervised Discretize issue and error during attribute selection "Not enough training instances"

I've been learning the Weka API on my own for the past month or so (I'm a student). What I am doing is writing a program that will filter a specific set of data and eventually build a bayes net for it, and a week ago I had finished my discretization class and attribute selection class. Just a few days ago I realized that I needed to change my discretization function to supervised and ended up using the default Fayyad & Irani method, after I did this I began to get this error in my attribute selection class:
Exception in thread "main" weka.core.WekaException:
weka.attributeSelection.CfsSubsetEval: Not enough training instances with class labels (required: 1, provided: 0)!
at weka.core.Capabilities.test(Capabilities.java:1138)
at weka.core.Capabilities.test(Capabilities.java:1023)
at weka.core.Capabilities.testWithFail(Capabilities.java:1302)
at weka.attributeSelection.CfsSubsetEval.buildEvaluator(CfsSubsetEval.java:331)
at weka.attributeSelection.AttributeSelection.SelectAttributes(AttributeSelection.java:597)
at weka.filters.supervised.attribute.AttributeSelection.batchFinished(AttributeSelection.java:456)
at weka.filters.Filter.useFilter(Filter.java:663)
at AttributeSelectionFilter.selectionFilter(AttributeSelectionFilter.java:29)
at Runner.main(Runner.java:70)
My attribute selection before the change worked just fine, so I think that I may have done something wrong in my discretize class. My other part of this question relates to that, because I also noticed that my discretize class does not appear to really be discretizing the data; it's just putting all the numeric data into ONE range, not binning it strategically like the Fayyad & Irani should.
Here is my discretize class:
import weka.core.Instances;
import weka.filters.Filter;
import weka.filters.supervised.attribute.Discretize;
import weka.filters.unsupervised.attribute.NumericToNominal;
public class DiscretizeFilter
{
private Instances data;
private boolean sensitiveOption;
private Filter filter = new Discretize();
public DiscretizeFilter(Instances data, boolean sensitiveOption)
{
this.data = data;
this.sensitiveOption = sensitiveOption;
}
public Instances discreteFilter() throws Exception
{
NumericToNominal nm = new NumericToNominal();
nm.setInputFormat(data);
Filter.useFilter(data, nm);
Instances nominalData = nm.getOutputFormat();
if(sensitiveOption)//if the user wants extra sensitivity
{
String options[] = new String[1];
options[0] = options[0];
options[2] = "-E";
((Discretize) filter).setOptions(options);
}
filter.setInputFormat(nominalData);
Filter.useFilter(nominalData,filter);
return filter.getOutputFormat();
}
}
Here is my attribute selection class:
import weka.attributeSelection.BestFirst;
import weka.attributeSelection.CfsSubsetEval;
import weka.core.Instances;
import weka.filters.supervised.attribute.AttributeSelection;
public class AttributeSelectionFilter
{
public Instances selectionFilter(Instances data) throws Exception
{
AttributeSelection filter = new AttributeSelection();
for(int i = 0; i < data.numInstances(); i++)
{
filter.input(data.instance(i));
}
CfsSubsetEval eval = new CfsSubsetEval();
BestFirst search = new BestFirst();
filter.setSearch(search);
filter.setEvaluator(eval);
filter.setInputFormat(data);
AttributeSelection.useFilter(data, filter);
return filter.getOutputFormat();
}
public int attributeCounter(Instances data)
{
return data.numAttributes();
}
}
Any help would be greatly appreciated!!!
Internally Weka stores attribute values as doubles. It appears that an exception was thrown because every single instance in your dataset (data) is "missing a class", i.e. was given an internal class attribute value NaN ("not a number") for whatever reason. I would recommend to double-check if data's class attribute was created/set correctly.
I figured it out, it was my mistake of misunderstanding the description of the method "outputFormat()" in the Discretize class. I instead got the filtered instances from the useFilter() and that solved my problems! I was just giving the attribute selection filter the wrong type of data.

ConcurrentModificationException using Richfaces ExtendedDataTable

I apologize for a lengthy question, but I really need your help. As a part of our project, I'm currently working on a search engine, that updates results list on the fly: the user types in the first 4 characters and up, and as he types, the results list changes. The search value is typed in a text box, while the results are displayed in a Richfaces component rich:extendedDataTable below. If the search value is removed, the result list is empty. I was able to get that working, however, after a few tries I get ConcurrentModificationException, thrown by the component itself. The initial list I am searching comes from the properties file (because I don't want the search to hit database every time the user types something). I've been banging my head over it for months. What am I missing? Let me show you what I've done:
This is the input text that should trigger the search logic (I make sure that the table does not get updated when the value is less than 4 characters or if the user presses keys, like arrows, shift, and ctrl - this function is "returnunicode(event)"):
<h:inputText id="firmname" value="#{ExtendedTableBean.searchValue}">
<a4j:support reRender="resultsTable" onsubmit="
if ((this.value.length<4 && this.value.length>0) || !returnunicode(event)) {
return false;
}" actionListener="#{ExtendedTableBean.searchForResults}" event="onkeyup" />
</h:inputText>
Action listener is what should update the list. Here is the extendedDataTable, right below the inputText:
<rich:extendedDataTable tableState="#{ExtendedTableBean.tableState}" var="item"
id="resultsTable" value="#{ExtendedTableBean.dataModel}">
... <%-- I'm listing columns here --%>
</rich:extendedDataTable>
Now, if it's ok, I would like to show you the back-end code. I only left the logic that's important to my issue.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.beans;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import org.richfaces.model.DataProvider;
import org.richfaces.model.ExtendedTableDataModel;
public class ExtendedTableBean {
private String sortMode="single";
private ExtendedTableDataModel<ResultObject> dataModel;
//ResultObject is a simple pojo and getResultsPerValue is a method that
//read the data from the properties file, assigns it to this pojo, and
//adds a pojo to the list
private Object tableState;
private List<ResultObject> results = new CopyOnWriteArrayList<ResultObject>();
private List<ResultObject> selectedResults =
new CopyOnWriteArrayList<ResultObject>();
private String searchValue;
/**
* This is the action listener that the user triggers, by typing the search value
*/
public void searchForResults(ActionEvent e) {
synchronized(results) {
results.clear();
}
//I don't think it's necessary to clear results list all the time, but here
//I also make sure that we start searching if the value is at least 4
//characters long
if (this.searchValue.length() > 3) {
results.clear();
updateTableList();
} else {
results.clear();
}
dataModel = null; // to force the dataModel to be updated.
}
public List<ResultObject> getResultsPerValue(String searchValue) {
List<ResultObject> resultsList = new CopyOnWriteArrayList<ResultObject>();
//Logic for reading data from the properties file, populating ResultObject
//and adding it to the list
return resultsList;
}
/**
* This method updates a firm list, based on a search value
*/
public void updateTableList() {
try {
List<ResultObject> searchedResults = getResultsPerValue(searchValue);
//Once the results have been retrieved from the properties, empty
//current firm list and replace it with what was found.
synchronized(firms) {
firms.clear();
firms.addAll(searchedFirms);
}
} catch(Throwable xcpt) {
//Exception handling
}
}
/**
* This is a recursive method, that's used to constantly keep updating the
* table list.
*/
public synchronized ExtendedTableDataModel<ResultObject> getDataModel() {
try {
if (dataModel == null) {
dataModel = new ExtendedTableDataModel<ResultObject>(
new DataProvider<ResultObject>() {
public ResultObject getItemByKey(Object key) {
try {
for(ResultObject c : results) {
if (key.equals(getKey(c))){
return c;
}
}
} catch (Exception ex) {
//Exception handling
}
return null;
}
public List<ResultObject> getItemsByRange(
int firstRow, int endRow) {
return Collections.unmodifiableList(results.subList(firstRow, endRow));
}
public Object getKey(ResultObject item) {
return item.getResultName();
}
public int getRowCount() {
return results.size();
}
});
}
} catch (Exception ex) {
//Exception handling
}
return dataModel;
}
//Getters and setters
}
And like I said, it works fine, but when the user types fast or deletes fast (it's hard to catch exactly when it happens), ConcurrentModificationException is thrown. Here's what it looks like exactly:
WARNING: executePhase(RENDER_RESPONSE 6,com.sun.faces.context.FacesContextImpl#4406b8) threw exception
java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
at java.util.AbstractList$Itr.next(AbstractList.java:343)
at org.richfaces.model.ExtendedTableDataModel.walk(ExtendedTableDataModel.java:108)
at org.ajax4jsf.component.UIDataAdaptorBase.walk(UIDataAdaptorBase.java:1156)
at org.richfaces.renderkit.AbstractExtendedRowsRenderer.encodeRows(AbstractExtendedRowsRenderer.java:159)
at org.richfaces.renderkit.AbstractExtendedRowsRenderer.encodeRows(AbstractExtendedRowsRenderer.java:142)
at org.richfaces.renderkit.AbstractExtendedRowsRenderer.encodeChildren(AbstractExtendedRowsRenderer.java:191)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:812)
at org.ajax4jsf.renderkit.RendererBase.renderChild(RendererBase.java:277)
at org.ajax4jsf.renderkit.AjaxChildrenRenderer.encodeAjaxComponent(AjaxChildrenRenderer.java:166)
at org.ajax4jsf.renderkit.AjaxChildrenRenderer.encodeAjaxChildren(AjaxChildrenRenderer.java:83)
at org.ajax4jsf.renderkit.AjaxChildrenRenderer.encodeAjaxComponent(AjaxChildrenRenderer.java:157)
...
Synchronization of the Java code has never been my strongest side, I don't know what would be causing the error and, most importantly, how can I get rid of it. I'm aware, that Richfaces 4.0 has made a lot of changes to rich:extendedDataTable component, I've heard that this was an issue before and now it's resolved. However, I don't have time to upgrade the whole application to Richfaces 4.0 (it's going to be done in phase 2), this is just the small part of the whole project. If there is no way to resolve the issue, described above, then maybe there's a workaround? Or, perhaps, there are other ways to implement similar kind of search, using plain JSF (provided that it's are quick enough to implement). I will appreciate any kind of help or advice on that matter. I hope the code is understandable enough, but if not, let me know, I'll explain further. Thank you in advance, I really appreciate your help.
The problem is concurrent ajax calls to the server. Use the attribute "eventsQueue" in a4j:support. Usually, you should always use "eventsQueue" in any ajax component, with all "eventsQueue" in the same page referencing the same queue, unless you have a very good reason to not doing it.
Also, you'll probably want to look into another ajax attribute: "ajaxSingle".

Seeking useful Eclipse Java code templates [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Improve this question
You can create various Java code templates in Eclipse via
Window > Preferences > Java > Editor > Templates
e.g.
sysout is expanded to:
System.out.println(${word_selection}${});${cursor}
You can activate this by typing sysout followed by CTRL+SPACE
What useful Java code templates do you currently use? Include the name and description of it and why it's awesome.
I am looking for an original/novel use of a template rather than a built-in existing feature.
Create Log4J logger
Get swt color from display
Syncexec - Eclipse Framework
Singleton Pattern/Enum Singleton Generation
Readfile
Const
Traceout
Format String
Comment Code Review
String format
Try Finally Lock
Message Format i18n and log
Equalsbuilder
Hashcodebuilder
Spring Object Injection
Create FileOutputStream
The following code templates will both create a logger and create the right imports, if needed.
SLF4J
${:import(org.slf4j.Logger,org.slf4j.LoggerFactory)}
private static final Logger LOG = LoggerFactory.getLogger(${enclosing_type}.class);
Log4J 2
${:import(org.apache.logging.log4j.LogManager,org.apache.logging.log4j.Logger)}
private static final Logger LOG = LogManager.getLogger(${enclosing_type}.class);
Log4J
${:import(org.apache.log4j.Logger)}
private static final Logger LOG = Logger.getLogger(${enclosing_type}.class);
Source.
JUL
${:import(java.util.logging.Logger)}
private static final Logger LOG = Logger.getLogger(${enclosing_type}.class.getName());
Some additional templates here: Link I -
Link II
I like this one:
readfile
${:import(java.io.BufferedReader,
java.io.FileNotFoundException,
java.io.FileReader,
java.io.IOException)}
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(${fileName}));
String line;
while ((line = in.readLine()) != null) {
${process}
}
}
catch (FileNotFoundException e) {
logger.error(e) ;
}
catch (IOException e) {
logger.error(e) ;
} finally {
if(in != null) in.close();
}
${cursor}
UPDATE: The Java 7 version of this template is:
${:import(java.nio.file.Files,
java.nio.file.Paths,
java.nio.charset.Charset,
java.io.IOException,
java.io.BufferedReader)}
try (BufferedReader in = Files.newBufferedReader(Paths.get(${fileName:var(String)}),
Charset.forName("UTF-8"))) {
String line = null;
while ((line = in.readLine()) != null) {
${cursor}
}
} catch (IOException e) {
// ${todo}: handle exception
}
Format a string
MessageFormat - surround the selection with a MessageFormat.
${:import(java.text.MessageFormat)}
MessageFormat.format(${word_selection}, ${cursor})
This lets me move a cursor to a string, expand the selection to the entire string (Shift-Alt-Up), then Ctrl-Space twice.
Lock the selection
lock - surround the selected lines with a try finally lock. Assume the presence of a lock variable.
${lock}.acquire();
try {
${line_selection}
${cursor}
} finally {
${lock}.release();
}
NB ${line_selection} templates show up in the Surround With menu (Alt-Shift-Z).
I know I am kicking a dead post, but wanted to share this for completion sake:
A correct version of singleton generation template, that overcomes the flawed double-checked locking design (discussed above and mentioned else where)
Singleton Creation Template:
Name this createsingleton
static enum Singleton {
INSTANCE;
private static final ${enclosing_type} singleton = new ${enclosing_type}();
public ${enclosing_type} getSingleton() {
return singleton;
}
}
${cursor}
To access singletons generated using above:
Singleton reference Template:
Name this getsingleton:
${type} ${newName} = ${type}.Singleton.INSTANCE.getSingleton();
Append code snippet to iterate over Map.entrySet():
Template:
${:import(java.util.Map.Entry)}
for (Entry<${keyType:argType(map, 0)}, ${valueType:argType(map, 1)}> ${entry} : ${map:var(java.util.Map)}.entrySet())
{
${keyType} ${key} = ${entry}.getKey();
${valueType} ${value} = ${entry}.getValue();
${cursor}
}
Generated Code:
for (Entry<String, String> entry : properties.entrySet())
{
String key = entry.getKey();
String value = entry.getValue();
|
}
For log, a helpful little ditty to add in the member variable.
private static Log log = LogFactory.getLog(${enclosing_type}.class);
Create a mock with Mockito (in "Java statements" context):
${:importStatic('org.mockito.Mockito.mock')}${Type} ${mockName} = mock(${Type}.class);
And in "Java type members":
${:import(org.mockito.Mock)}#Mock
${Type} ${mockName};
Mock a void method to throw an exception:
${:import(org.mockito.invocation.InvocationOnMock,org.mockito.stubbing.Answer)}
doThrow(${RuntimeException}.class).when(${mock:localVar}).${mockedMethod}(${args});
Mock a void method to do something:
${:import(org.mockito.invocation.InvocationOnMock,org.mockito.stubbing.Answer)}doAnswer(new Answer<Object>() {
public Object answer(InvocationOnMock invocation) throws Throwable {
Object arg1 = invocation.getArguments()[0];
return null;
}
}).when(${mock:localVar}).${mockedMethod}(${args});
Verify mocked method called exactly once:
${:importStatic(org.mockito.Mockito.verify,org.mockito.Mockito.times)}
verify(${mock:localVar}, times(1)).${mockMethod}(${args});
Verify mocked method is never invoked:
${:importStatic(org.mockito.Mockito.verify,org.mockito.Mockito.never)}verify(${mock:localVar}, never()).${mockMethod}(${args});
New linked list using Google Guava (and similar for hashset and hashmap):
${import:import(java.util.List,com.google.common.collect.Lists)}List<${T}> ${newName} = Lists.newLinkedList();
Also I use a huge template that generates a Test class. Here is a shortened fragment of it that everyone interested should customize:
package ${enclosing_package};
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
import org.mockito.Mockito;
import org.slf4j.Logger;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.junit.runner.RunWith;
// TODO autogenerated test stub
#RunWith(MockitoJUnitRunner.class)
public class ${primary_type_name} {
#InjectMocks
protected ${testedType} ${testedInstance};
${cursor}
#Mock
protected Logger logger;
#Before
public void setup() throws Exception {
}
#Test
public void shouldXXX() throws Exception {
// given
// when
// TODO autogenerated method stub
// then
fail("Not implemented.");
}
}
// Here goes mockito+junit cheetsheet
Null Checks!
if( ${word_selection} != null ){
${cursor}
}
if( ${word_selection} == null ){
${cursor}
}
One of my beloved is foreach:
for (${iterable_type} ${iterable_element} : ${iterable}) {
${cursor}
}
And traceout, since I'm using it a lot for tracking:
System.out.println("${enclosing_type}.${enclosing_method}()");
I just thought about another one and have found it over the Internet some day, const:
private static final ${type} ${name} = new ${type} ${cursor};
A little tip on sysout -- I like to renamed it to "sop". Nothing else in the java libs starts with "sop" so you can quickly type "sop" and boom, it inserts.
Throw an IllegalArgumentException with variable in current scope (illarg):
throw new IllegalArgumentException(${var});
Better
throw new IllegalArgumentException("Invalid ${var} " + ${var});
Nothing fancy for code production - but quite useful for code reviews
I have my template coderev low/med/high do the following
/**
* Code Review: Low Importance
*
*
* TODO: Insert problem with code here
*
*/
And then in the Tasks view - will show me all of the code review comments I want to bring up during a meeting.
Some more templates here.
Includes:
Create a date object from a particular date
Create a new generic ArrayList
Logger setup
Log with specified level
Create a new generic HashMap
Iterate through a map, print the keys and values
Parse a time using SimpleDateFormat
Read a file line by line
Log and rethrow a caught exeption
Print execution time of a block of code
Create periodic Timer
Write a String to a file
slf4j Logging
${imp:import(org.slf4j.Logger,org.slf4j.LoggerFactory)}
private static final Logger LOGGER = LoggerFactory
.getLogger(${enclosing_type}.class);
Bean Property
private ${Type} ${property};
public ${Type} get${Property}() {
return ${property};
}
public void set${Property}(${Type} ${property}) {
${propertyChangeSupport}.firePropertyChange("${property}", this.${property}, this.${property} = ${property});
}
PropertyChangeSupport
private PropertyChangeSupport ${propertyChangeSupport} = new PropertyChangeSupport(this);${:import(java.beans.PropertyChangeSupport,java.beans.PropertyChangeListener)}
public void addPropertyChangeListener(PropertyChangeListener listener) {
${propertyChangeSupport}.addPropertyChangeListener(listener);
}
public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) {
${propertyChangeSupport}.addPropertyChangeListener(propertyName, listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
${propertyChangeSupport}.removePropertyChangeListener(listener);
}
public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) {
${propertyChangeSupport}.removePropertyChangeListener(propertyName, listener);
}
Post Java 7, a great way to set up loggers which need (or prefer) static references to the enclosing class is to use the newly introduced MethodHandles API to get the runtime class in a static context.
An example snippet for SLF4J is:
private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
Aside from being a simple snippet in any IDE, it is also less brittle if you refactor certain functionality into another class because you won't accidentally carry the class name with it.
Invoke code on the GUI thread
I bind the following template to the shortcut slater to quickly dispatch code on the GUI thread.
${:import(javax.swing.SwingUtilities)}
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
${cursor}
}
});
When testing around with code I sometimes missed out on deleting some syso s. So I made myself a template called syt.
System.out.println(${word_selection}${});//${todo}:remove${cursor}
Before I compile I always check my TODOs and will never forget to delete a System.out again.
strf -> String.format("msg", args) pretty simple but saves a bit of typing.
String.format("${cursor}",)
Get an SWT color from current display:
Display.getCurrent().getSystemColor(SWT.COLOR_${cursor})
Suround with syncexec
PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable(){
public void run(){
${line_selection}${cursor}
}
});
Use the singleton design pattern:
/**
* The shared instance.
*/
private static ${enclosing_type} instance = new ${enclosing_type}();
/**
* Private constructor.
*/
private ${enclosing_type}() {
super();
}
/**
* Returns this shared instance.
*
* #returns The shared instance
*/
public static ${enclosing_type} getInstance() {
return instance;
}
And an equalsbuilder, hashcodebuilder adaptation:
${:import(org.apache.commons.lang.builder.EqualsBuilder,org.apache.commons.lang.builder.HashCodeBuilder)}
#Override
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
#Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
The template for the logger declaration is great.
I also create linfo, ldebug, lwarn, lerror for the log levels that I use more often.
lerror:
logger.error(${word_selection}${});${cursor}
Create everything for an event
Since events are kinda a pain to create in Java--all those interfaces, methods, and stuff to write just for 1 event--I made a simple template to create everything needed for 1 event.
${:import(java.util.List, java.util.LinkedList, java.util.EventListener, java.util.EventObject)}
private final List<${eventname}Listener> ${eventname}Listeners = new LinkedList<${eventname}Listener>();
public final void add${eventname}Listener(${eventname}Listener listener)
{
synchronized(${eventname}Listeners) {
${eventname}Listeners.add(listener);
}
}
public final void remove${eventname}Listener(${eventname}Listener listener)
{
synchronized(${eventname}Listeners) {
${eventname}Listeners.remove(listener);
}
}
private void raise${eventname}Event(${eventname}Args args)
{
synchronized(${eventname}Listeners) {
for(${eventname}Listener listener : ${eventname}Listeners)
listener.on${eventname}(args);
}
}
public interface ${eventname}Listener extends EventListener
{
public void on${eventname}(${eventname}Args args);
}
public class ${eventname}Args extends EventObject
{
public ${eventname}Args(Object source${cursor})
{
super(source);
}
}
If you have events that share a single EventObject, just delete the customized one inserted by the template and change the appropriate parts of raise___() and on____().
I had written a nice, little, elegant eventing mechanism using a generic interface and generic class, but it wouldn't work due to the way Java handles generics. =(
Edit:
1) I ran into the issue where threads were adding/removing listeners while an event was taking place. The List can't be modified while in use, so I added synchronized blocks where the list of listeners is being accessed or used, locking on the list itself.
Insert test methods should-given-when-then
I saw a similar version to this one recently while pair programming with a very good developer and friend, and I think it could be a nice addition to this list.
This template will create a new test method on a class, following the Given - When - Then approach from the behavior-driven development (BDD) paradigm on the comments, as a guide for structuring the code. It will start the method name with "should" and let you replace the rest of the dummy method name "CheckThisAndThat" with the best possible description of the test method responsibility. After filling the name, TAB will take you straight to the // Given section, so you can start typing your preconditions.
I have it mapped to the three letters "tst", with description "Test methods should-given-when-then" ;)
I hope you find it as useful as I did when I saw it:
#Test
public void should${CheckThisAndThat}() {
Assert.fail("Not yet implemented");
// Given
${cursor}
// When
// Then
}${:import(org.junit.Test, org.junit.Assert)}
Spring Injection
I know this is sort of late to the game, but here is one I use for Spring Injection in a class:
${:import(org.springframework.beans.factory.annotation.Autowired)}
private ${class_to_inject} ${var_name};
#Autowired
public void set${class_to_inject}(${class_to_inject} ${var_name}) {
this.${var_name} = ${var_name};
}
public ${class_to_inject} get${class_to_inject}() {
return this.${var_name};
}
Here is a constructor for non-instantiable classes:
// Suppress default constructor for noninstantiability
#SuppressWarnings("unused")
private ${enclosing_type}() {
throw new AssertionError();
}
This one is for custom exceptions:
/**
* ${cursor}TODO Auto-generated Exception
*/
public class ${Name}Exception extends Exception {
/**
* TODO Auto-generated Default Serial Version UID
*/
private static final long serialVersionUID = 1L;
/**
* #see Exception#Exception()
*/
public ${Name}Exception() {
super();
}
/**
* #see Exception#Exception(String)
*/
public ${Name}Exception(String message) {
super(message);
}
/**
* #see Exception#Exception(Throwable)
*/
public ${Name}Exception(Throwable cause) {
super(cause);
}
/**
* #see Exception#Exception(String, Throwable)
*/
public ${Name}Exception(String message, Throwable cause) {
super(message, cause);
}
}
I like a generated class comment like this:
/**
* I...
*
* $Id$
*/
The "I..." immediately encourages the developer to describe what the class does. I does seem to improve the problem of undocumented classes.
And of course the $Id$ is a useful CVS keyword.
I've had a lot of use of these snippets, looking for null values and empty strings.
I use the "argument test"-templates as the first code in my methods to check received arguments.
testNullArgument
if (${varName} == null) {
throw new NullPointerException(
"Illegal argument. The argument cannot be null: ${varName}");
}
You may want to change the exception message to fit your company's or project's standard. However, I do recommend having some message that includes the name of the offending argument. Otherwise the caller of your method will have to look in the code to understand what went wrong. (A NullPointerException with no message produces an exception with the fairly nonsensical message "null").
testNullOrEmptyStringArgument
if (${varName} == null) {
throw new NullPointerException(
"Illegal argument. The argument cannot be null: ${varName}");
}
${varName} = ${varName}.trim();
if (${varName}.isEmpty()) {
throw new IllegalArgumentException(
"Illegal argument. The argument cannot be an empty string: ${varName}");
}
You can also reuse the null checking template from above and implement this snippet to only check for empty strings. You would then use those two templates to produce the above code.
The above template, however, has the problem that if the in argument is final you will have to amend the produced code some (the ${varName} = ${varName}.trim() will fail).
If you use a lot of final arguments and want to check for empty strings but doesn't have to trim them as part of your code, you could go with this instead:
if (${varName} == null) {
throw new NullPointerException(
"Illegal argument. The argument cannot be null: ${varName}");
}
if (${varName}.trim().isEmpty()) {
throw new IllegalArgumentException(
"Illegal argument. The argument cannot be an empty string: ${varName}");
}
testNullFieldState
I also created some snippets for checking variables that is not sent as arguments (the big difference is the exception type, now being an IllegalStateException instead).
if (${varName} == null) {
throw new IllegalStateException(
"Illegal state. The variable or class field cannot be null: ${varName}");
}
testNullOrEmptyStringFieldState
if (${varName} == null) {
throw new IllegalStateException(
"Illegal state. The variable or class field cannot be null: ${varName}");
}
${varName} = ${varName}.trim();
if (${varName}.isEmpty()) {
throw new IllegalStateException(
"Illegal state. The variable or class field " +
"cannot be an empty string: ${varName}");
}
testArgument
This is a general template for testing a variable. It took me a few years to really learn to appreciate this one, now I use it a lot (in combination with the above templates of course!)
if (!(${varName} ${testExpression})) {
throw new IllegalArgumentException(
"Illegal argument. The argument ${varName} (" + ${varName} + ") " +
"did not pass the test: ${varName} ${testExpression}");
}
You enter a variable name or a condition that returns a value, followed by an operand ("==", "<", ">" etc) and another value or variable and if the test fails the resulting code will throw an IllegalArgumentException.
The reason for the slightly complicated if clause, with the whole expression wrapped in a "!()" is to make it possible to reuse the test condition in the exception message.
Perhaps it will confuse a colleague, but only if they have to look at the code, which they might not have to if you throw these kind of exceptions...
Here's an example with arrays:
public void copy(String[] from, String[] to) {
if (!(from.length == to.length)) {
throw new IllegalArgumentException(
"Illegal argument. The argument from.length (" +
from.length + ") " +
"did not pass the test: from.length == to.length");
}
}
You get this result by calling up the template, typing "from.length" [TAB] "== to.length".
The result is way funnier than an "ArrayIndexOutOfBoundsException" or similar and may actually give your users a chance to figure out the problem.
Enjoy!
I use this for MessageFormat (using Java 1.4). That way I am sure that I have no concatenations that are hard to extract when doing internationalization
i18n
String msg = "${message}";
Object[] params = {${params}};
MessageFormat.format(msg, params);
Also for logging:
log
if(logger.isDebugEnabled()){
String msg = "${message}"; //NLS-1
Object[] params = {${params}};
logger.debug(MessageFormat.format(msg, params));
}
My favorite few are...
1: Javadoc, to insert doc about the method being a Spring object injection method.
Method to set the <code>I${enclosing_type}</code> implementation that this class will use.
*
* #param ${enclosing_method_arguments}<code>I${enclosing_type}</code> instance
2: Debug window, to create a FileOutputStream and write the buffer's content's to a file.
Used for when you want to compare a buffer with a past run (using BeyondCompare), or if you can't view the contents of a buffer (via inspect) because its too large...
java.io.FileOutputStream fos = new java.io.FileOutputStream( new java.io.File("c:\\x.x"));
fos.write(buffer.toString().getBytes());
fos.flush();
fos.close();

Categories