I want to write test case for below protected final method in java using EasyMock. Is there any way to write test case of protected final method using EasyMock ?
I tried to write TC using Reflection approach,but it didn't work.
Class < ? extends Entity > type;
private Filter filter;
private Input input;
private transient Service access;
private transient ConfigDao confdao;
protected final Limitation getBaseLimitation() {
Validate.notNull(type);
GroupClass Group = new GroupClass(GroupTypeClass.SELECTOR);
if (A.class.isAssignableFrom(type)) {
filter = new Simple(A.ATTRIBUTE_ACTIVE, Operator.EQUALS, Boolean.TRUE); //A class has static final static String ATTRIBUTE_ACTIVE = "Active";
}
if (G.class.isAssignableFrom(type)) {
filter = new Simple("position", Operator.EQUALS, Position.ACTIVE);
}
if (Boolean.TRUE.equals(confdao.getconfdao().getarea())) {
if (U.class.isAssignableFrom(type)) {
Validate.notNull(input, "switched on.");
Object Inputobj = input.getInput();
return access.getBaseLimitation(type, Inputobj, Group, filter);
}
}
return access.getBaseLimitation(type, Group, filter);
}
public Simple(String path, Operator operator, Object value) {
this(Path, operator, new Object[]{value});
}
Any help would be appreciated.
If you are mocking getBaseLimitation(), no, EasyMock can't help you because final methods can't be overridden. PowerMock could help you but I would personally just drop the final.
If you are testing it, you can from a class in the same package. But EasyMock is not needed to do so.
Then, protected final is not something useful. Why being protected if you don't want to be overloaded? You better be package scope or private.
Related
Due to a specific reason, I would like to use Checker Framework and its subtyping checker.
To make this checker work I have to use ElementType.TYPE_PARAMETER and ElementType.TYPE_USE.
However, I would like to remove them from local variables before compilation to class files.
For example, let's say I have the following code with custom #FirstName and #LastName (both must retain at the class level with RetentionPolicy.CLASS):
#FirstName String firstName = ...;
#LastName String lastName = ...;
...
firstName = lastName; // illegal, the error is generated by Checker Framework because the first name cannot be assigned to the last name
but for another reason, I would like to remove the annotations from the local variables "at" bytecode level as if the source code is just:
String firstName = ...;
String lastName = ...;
...
firstName = lastName; // totally fine and legal in Java
If I understand the way it can be accomplished, annotation processing is a way to go.
So, if it's a right thing to do, then I'd have to chain some annotation processors in the following order:
org.checkerframework.common.subtyping.SubtypingChecker.
my custom "remove local variables annotations" annotation processor;
Well, diving into how javac works is an extreme challenge to me.
What I have implemented so far is:
#SupportedOptions(RemoveLocalVariableAnnotationsProcessor.ANNOTATIONS_OPTION)
#SupportedAnnotationTypes("*")
#SupportedSourceVersion(SourceVersion.RELEASE_8)
public final class RemoveLocalVariableAnnotationsProcessor
extends AbstractProcessor {
private static final Pattern commaPattern = Pattern.compile(",");
static final String ANNOTATIONS_OPTION = "RemoveLocalVariableAnnotationsProcessor.annotations";
#Nonnull
private Predicate<? super Class<? extends Annotation>> annotationClasses = clazz -> false;
#Override
public void init(#Nonnull final ProcessingEnvironment environment) {
super.init(environment);
final Messager messager = environment.getMessager();
final Map<String, String> options = environment.getOptions();
#Nullable
final String annotationsOption = options.get(ANNOTATIONS_OPTION);
if ( annotationsOption != null ) {
annotationClasses = commaPattern.splitAsStream(annotationsOption)
.<Class<? extends Annotation>>flatMap(className -> {
try {
#SuppressWarnings("unchecked")
final Class<? extends Annotation> clazz = (Class<? extends Annotation>) Class.forName(className);
if ( !clazz.isAnnotation() ) {
messager.printMessage(Diagnostic.Kind.WARNING, "Not an annotation: " + className);
return Stream.empty();
}
return Stream.of(clazz);
} catch ( final ClassNotFoundException ex ) {
messager.printMessage(Diagnostic.Kind.WARNING, "Cannot find " + className);
return Stream.empty();
}
})
.collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet))
::contains;
}
final Trees trees = Trees.instance(environment);
final JavacTask javacTask = JavacTask.instance(environment);
javacTask.addTaskListener(new RemoverTaskListener(trees, messager));
}
#Override
public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment environment) {
// do nothing: ElementType.TYPE_USE and ElementType.TYPE_PARAMETER seem to be unable to be analyzed here
return false;
}
private static final class RemoverTaskListener
implements TaskListener {
private final Trees trees;
private final Messager messager;
private RemoverTaskListener(final Trees trees, final Messager messager) {
this.trees = trees;
this.messager = messager;
}
#Override
public void started(final TaskEvent taskEvent) {
if ( taskEvent.getKind() == TaskEvent.Kind.ANALYZE ) {
final TreeScanner<?, ?> remover = new Remover(trees, messager);
remover.scan(taskEvent.getCompilationUnit(), null);
}
}
#Override
public void finished(final TaskEvent taskEvent) {
// do nothing
}
private static final class Remover
extends TreePathScanner<Void, Void> {
private final Trees trees;
private final Messager messager;
private Remover(final Trees trees, final Messager messager) {
this.trees = trees;
this.messager = messager;
}
#Override
public Void visitVariable(final VariableTree variableTree, final Void nothing) {
super.visitVariable(variableTree, nothing);
final Symbol symbol = (Symbol) trees.getElement(trees.getPath(getCurrentPath().getCompilationUnit(), variableTree));
if ( !symbol.hasTypeAnnotations() || symbol.getKind() != ElementKind.LOCAL_VARIABLE ) {
return nothing;
}
final List<? extends AnnotationTree> annotationTrees = variableTree.getModifiers().getAnnotations();
if ( annotationTrees.isEmpty() ) {
return nothing;
}
messager.printMessage(Diagnostic.Kind.WARNING, "TODO: " + symbol);
for ( final AnnotationTree annotationTree : annotationTrees ) {
// TODO how to align AnnotationTree and java.lang.annotation.Annotation?
// TODO how to remove the annotation from the local variable?
}
return nothing;
}
}
}
}
As you can see, it does not work as it's supposed to do.
What is a proper way of removing the annotations from local variables?
I mean, how do I accomplish it?
If it's possible, I would like to stick to javac annotation processors due to the Maven build integration specifics.
As far as I know, you can't do it this way:
javac annotation processors (JSR-269) can't modify code. They can only observe it and generate new code that will be compiled together with the hand-written code. Thus, annotation processing is done in multiple rounds to allow compiler and other annotation processors see the newly generated code. The processing stops basically when no new code is generated at the end of the round.
This way the order of annotation processor invocations is not defined, and that's okay, because of multi-round compilation - it helps solving cyclic dependencies.
What you need is a bytecode rewriter (ASM library would do well). Such tools operate on resulting .class files after compilation is done. Yet again, AFAIK, annotation processing is embedded into compilation itself, so you won't be able to rewrite bytecode before Checker annotation processor sees it.
So, sadly, I don't see any solution, but to try and fork the Checker Framework and make it ignore annotations you want, if of course it doesn't already have options to turn certain validations off.
I have this code:
public class Compiler {
public void compile(String template, Object o, Object params) {
//...
context(o, params);
//...
}
private void context(Object o, Object params) {
//...
substitue(o, params);
//...
}
private void substitue(Object o, Object params) {
//...
print(params);
//...
}
private void print(Object params) {//use parameter params here, only here
//...
System.out.println(params);
//...
}
}
As you can see, the parameter params is used only in the print method, not in compile, context or substitue. The problem is adding the params to the signature of all the methods down to print.
In general, when I'm facing this problem I refactor my code like the following :
public class Compiler {
public void compile(String template, Object o, Object params) {
//...
new InnerCompiler(template, o, params).compile();
//...
}
private static class InnerCompiler {
private final String template;
private final Object o;
private final Object params;
InnerCompiler(String template, Object o, Object params) {
this.template = template;
this.o = o;
this.params = params;
}
private void compile() {
//...
context();
//...
}
private void context() {
//...
substitue();
//...
}
private vois substitue() {
//...
print();
//...
}
private void print() {
//...
System.out.println(this.params);
//...
}
}
}
This is a very basic example to illustrate the case of passing a parameter to all the methods even if it is not used by the method itself but by the next one (or deeper).
I'm looking for the name of this problem (maybe an anti-pattern). In the title I've put (Parameter traversal) but it could be wrong or it means another thing.
The first version of your code where you were passing parameters repeatedly down through the call-stack is referred to as "tramp data". You can read about it in a similar question on the Software Engineering site. What I think you're trying to do is to use Dependency Injection. I say "trying" because you're not injecting your dependencies into the Compiler instance, itself.
Instead, I would argue that what you're actually using is a really small version of the Bounded Context pattern. By this, I mean that your InnerCompiler class is a bounded context as described in Domain-Driven Design and might be more aptly named: CompilerContext. That being said, bounded contexts are usually domain level constructs that you are using to encapsulate complicated service-level data sets. A set of three parameters don't usually merit the term "bounded context", but that threshold is pretty subjective IMO, and you might be oversimplifying your code here for the sake of an easily understandable MCVE.
To use the DI pattern in a more standard form, I would change your code to something like the following:
public class Compiler {
private final String template;
private final Object o;
private final Object params;
Compiler(String template, Object o, Object params) {
this.template = template;
this.o = o;
this.params = params;
}
public void compile() {
//...
context();
//...
}
private void context() {
//...
substitute();
//...
}
private void substitute() {
//...
print();
//...
}
private void print() {
//...
System.out.println(this.params);
//...
}
}
This achieves what you're doing right now, without resorting to an artificial inner class.
Note that if you truly need something like a compiler to be used as a singleton as you have in your version of the code, consider using a CompilerFactory class with a newCompiler() method which would call the constructor and inject the dependencies.
I hope this answers your question. I know that this answer isn't a pattern out of the Design Patterns book by the Gang of Four, but IMO none of the patterns in that book truly reflect your code or your intent.
What you are trying to do seems to me to change parameter passing to global state.
I wonder what is the best practice of having some global mapping in a Java application?
Say I have a text file with the mapping:
key1:value1
key2:value2
...
keyN:valueN
The file is huge, and both keys and values are arbitrary, so I can't really use Enum.
In the Java application I'm going to instantiate a bunch of classes with keys as the input (note that the code is more adequate in reality, just trying to put it abstract and simple):
for(int i = 0; i < 10000; i++) {
String key = magicallyGetArbitaryKey();
SomeClass someClass = new SomeClass(key);
//do stuff
}
and assign a property in the constructor based on the map lookup.
public class SomeClass {
private String value;
public void SomeClass(String key) {
this.value = getValue(key);
}
private String getValue() {
// what is the best way to implement this?
}
}
I want my code to be simple and, what is important, testable. And avoid using frameworks such as Spring.
This is what I came up with so far: create a Holder class, which is simply a wrapper around the HashMap with the additional methods for initialization:
class MappingHolder {
private Map<String, String> keyValueMap = new HashMap();
public MappingHolder(String filePath){
keyValueMap = ...; //init from the file
}
public MappingHolder(Map initMap) { //constructor useful for testing
keyValueMap = initMap;
}
public String get(String key) {
return keyValueMap.get(key);
}
It seems to be obvious that I want to have only one instance of the mapping.
As far as I can see the options are:
Have the MappingHolder#getValue as a static method
public class SomeClass {
...
private String getValue() {
return MappingHolder.getValue()
}
Have the MappingHolder#getValue as an instance method, but make
field of the type MappingHolder static in the SomeClass
public class SomeClass {
...
private static MappingHolder mappingHolder = new MappingHolder();
private String getValue() {
return mappingHolder.getValue();
}
Make the MapppingHolder a singleton.
public class SomeClass {
...
private MappingHolder mappingHolder = MappingHolder.getInstance();
private String getValue() {
return mappingHolder.getValue();
}
Neither of this seems to me testable, having just JUnit and Mockito and not leveraging some more powerful mocking frameworks. Though I sucks in testing and maybe I am wrong.
So it would be great if one could recommend the approach, either how to develop further my own, or better one which I may be missing. Thanks!
I'm working with the Java AWS API to monitor some EC2 instances and on every refresh I need to query the service which returns a bunch of Instance objects (freshly constructed). I want to extend the functionality of these objects, I figure I can maintain a map of MyInstance objects which can be refreshed with the new Instances on each poll.
Now I could easily do this with a simple wrapper class that holds the original Instance as a property the issue is I would like to keep access to the base Instance API as I already use these functions in my code. Would it be possible to replace only the super-class parts of an instantiated object? Contrived example of what I'm going for:
class Instance {
protected int prop;
public Instance(int prop) {
this.prop = prop;
}
}
class MyInstance extends Instance {
protected int prop2;
public MyInstance(int prop, int prop2) {
super(prop);
this.prop2 = prop2;
}
}
MyInstance foo = new MyInstance(1, 2);
Instance foster = new Instance(3);
//what i want to do
foo.adoptedBy(foster);
//with the result that foo.prop == 3
Obviously this example would be trivial to transform but in my actual case there are far more properties that need to be transferred. Can Reflection do this? What kind of performance impact am I looking at if I use Reflection for 10 of these every second? Thanks for reading!
The best solution is to combine both your ideas:
Wrap the original Instance in a class that extends the Instance class. (In the constructor of the child class, you can create a new Instance object and set it)
Delegate all methods to the wrapped instance (and add new properties)
In your foster method, you simply change the wrapped Instance.
class Instance {
private int prop;
public Instance(int prop) {
this.prop = prop;
}
public int getProp() {
return prop;
}
}
class MyInstance extends Instance {
private Instance delegate;
private int prop2;
public MyInstance(Instance delegate, int prop2) {
super(prop);
this.delegate = delegate;
this.prop2 = prop2;
}
#Override
public int getProp() {
return delegate.getProp();
}
public int getProp2() {
return prop2;
}
public void foster(Instance i) {
delegate = i;
}
}
MyInstance foo = new MyInstance(1, 2);
Instance foster = new Instance(3);
//what i want to do
foo.adoptedBy(foster);
//with the result that foo.getProp() == 3
I have a public class, which needs 7 parameters to be passed down. At the moment, I am able to make 3 of them being passed to constructor and another 4 to a public method in the class . Like this:
Public Class AClass{
private XClass axClass;
private String par4;
private String par5;
private String par6;
private String par7;
public AClass(String par1, String par2, String par3){
aXClass = new XClass(par1,par2,par3);
}
public execute(String par4,String par5, String par6, String par7){
//this is needed because they are used in other private methods in this class
this.par4 = par4;
this.par5 = par5;
this.par6 = par6;
this.par7 = par7;
//call other private methods within this class.
//about 7 lines here
}
}
My question is, is this the right way to ask client of the class to passing in paramters?
There shouldn't be anything stopping you from passing 7 parameters to a constructor, if that's what you want. I don't know if there's a maximum number of parameters that can be passed to a method in Java, but it's certainly higher than 7 if there is a max.
When you create a class and its public methods, you're creating an interface on how to use and access that class. So technically what you've done so far is correct. Is it the "right way" to ask the client of a class to pass in arguments? That's up to you, the designer of the interface.
My first instinct when I saw 7 parameters being passed was to silently ask "Is there some relationship between some or all of these parameters that might mean they'd go together well in a class of their own?" That might be something you address as you look at your code. But that's a question of design, not one of correctness.
I'd go for the Builder Pattern instead of many constructor parameters as suggested by
Effective Java Item 2: Consider a builder when faced with many constructor parameters
Here's a simple class to illustrate:
public class Dummy {
private final String foo;
private final String bar;
private final boolean baz;
private final int phleem;
protected Dummy(final Builder builder) {
this.foo = builder.foo;
this.bar = builder.bar;
this.baz = builder.baz;
this.phleem = builder.phleem;
}
public String getBar() {
return this.bar;
}
public String getFoo() {
return this.foo;
}
public int getPhleem() {
return this.phleem;
}
public boolean isBaz() {
return this.baz;
}
public static class Builder {
private String foo;
private String bar;
private boolean baz;
private int phleem;
public Dummy build() {
return new Dummy(this);
}
public Builder withBar(final String bar) {
this.bar = bar;
return this;
}
public Builder withBaz(final boolean baz) {
this.baz = baz;
return this;
}
public Builder withFoo(final String foo) {
this.foo = foo;
return this;
}
public Builder withPhleem(final int phleem) {
this.phleem = phleem;
return this;
}
}
}
You would instantiate it like this:
Dummy dummy = new Dummy.Builder()
.withFoo("abc")
.withBar("def")
.withBaz(true)
.withPhleem(123)
.build();
The nice part: you get all the benefits of constructor parameters (e.g. immutability if you want it), but you get readable code too.
Can't you just make a class/hashmap that stores these parameters and pass this to the function?
public excute(Storageclass storageClass){
//this is needed because they are used in other private methods in this class
this.par4 = storageClass.getPar4();
this.par5 = storageClass.getPar5();
this.par6 = storageClass.getPar6();
this.par7 = storageClass.getPar7();
//or
this.storageClass = storageClass;
}
I don't really see the problem with that.
In any case you could create a "Request" object or something like this:
class SomeClass {
private String a;
private String b;
....
public SomeClass( Request r ) {
this.a = r.get("a");
this.b = r.get("b");
...
}
public void execute( Request other ) {
this.d = other.get("d");
this.e = other.get("d");
...
}
}
See also: http://c2.com/cgi/wiki?TooManyParameters
Without knowing the use of the child class, I can say that there is nothing inherently wrong with what you have done.
Note though that you have to declare
private XClass axClass;
in the variables of your AClass.
However, you say 'I am able to make....' Does this mean there is some problem with declaring this another way?
I don't care for it much, because an object should be 100% ready to be used after its constructor is called. It's not as written in your example.
If the parameters passed into the execute method can simply be consumed, and that's the method of interest for clients, I see no reason for them to be data members in the class.
Without knowing more about your ultimate aims it's hard to tell. But I would re-think this implementation.
If you're planning on introducing an AClass.someMethod() that needs to know par4-7 without requiring you to have called AClass.excute(), then clearly you should be passing the parameters in the constructor.
On the other hand: if you can construct an instance of this object with only par1-3 and do something meaningful with it besides call excute() then it makes sense to allow the object to be constructed with fewer than the full seven parameters.
Yet my own aesthetic is to try and limit the number of "modes" that an object can be in which make certain methods work and others fail. So ideally, a fully-constructed object is ready to run any method the programmer might call. I'd worry about the design issue more than be too concerned about the sheer number of parameters to the constructor.
But as others have pointed out, sometimes there is a natural grouping of these parameters which can deserve objects of their own. For instance: in many APIs instead of passing (x, y, width, height) all over the place they use rectangle objects.
As others already wrote, it is technically correct to pass 7 parameters, although not very 'user-friendly', if you can say so.
Since you didn't write much about this class, I can suggest one small thing: in constructor you're just creating XClass object, so it would be sane to create this object before and pass it as a single parameter.
Something like this:
...
XClass aXClass = new XClass(par1, par2, par3);
AClass aClass = new AClass(aXClass);
...
And this is the constructor:
public AClass(XClass aXClass) {
this.aXClass = aXClass;
}