Testing all classes which implement an interface in Java - java

Is there anything out there (for Java specifically) that allow you to automatically test the behavior of an interface? As an example, let's say I have a bunch of tests for the Comparable interface, that should apply to anything that implements Comparable. What I'd like is to be able to include "ComparableTests" automatically in the test fixtures for any of my classes which implement Comparable. Bonus points if this would work with generic interfaces.
I know the .NET framework mbUnit has something similar, and when you're using something like TestNG's generator functions you could set up a test fixture for Comparable and have the generator create an instance of each of your classes that implement Comparable. But I'd rather have it be automatic, and located at the test fixture for each of my classes (since I'll already have them around for testing other parts of that class).
Clarification: I could definitely build something like this. I was asking if there was anything out there that already enabled this.

Based on your last paragraph, what you're trying to do is inject some 'extra methods' into unit testing since you're already testing a specific class. I do not know of a testing harness that allows you to attach tests based on the hierarchy of a class.
However, with your own suggestion of using TestNG for building something similar, I think you might be very close. You could very well incorporate some base code that adds your class to a list of 'default test classes', which are in turn tested if they implement a specific interface.
Still, regarding the general case, I think you're out of luck, since the Java type system is one-way, you can only (easily) find out what interfaces a class implements, not the other way around. Furthermore, the problem is 'where to stop looking': if you have a test that checks all your comparable implementers, do you want it to check the validity of String's one too, since that is in your Java environment?

Try this
http://www.xmlizer.biz/java/classloader/ClassList.java

In .NET it would be pretty simple to set up a method that looks through an assembly and identifies each class's inheritance/implementation hierarchy. I'm sure you could do it in Java, too, if you research the Java reflection API.
You could then create an array of ITargetInterfaces and call a test method on each one.

One way would be to search through the jar file for all the .class files (or search through the classes directory), use the Class.forName() method to load the class file and check MyInterface.class.isAssignableFrom(myClass).
This wouldn't deal easily public inner static classes (you could parse the class file name), but would never work with private inner classes or anonymous inner classes.

Related

Adding method in an existing interface which has different implementations in large number of classes

If we have an interface which is being implemented by large number of classes in our application, and we need to add a method to the interface, What is the recommended way to do it?
Would the approach differ if we are using older version of java (let's say 1.5) vs if we are using newer version of java (let's say 1.8).
This won't be a popular answer, but it seems right to me that the operation you envisage is a difficult one.
Interfaces define a service contract between different sub-systems. Changing that contract should be more difficult that changing an implementation. Java 8 introduced "default" methods on interfaces, which converts the interface from being a strict contract, to a kind of abstract base class. I guess it might take some of the sting out of changing interfaces, but I think it's right that developers should feel that sting.
In fact, in an ideal world, all interfaces would be agreed in advance, and there should never be a need to change one. I guess that's impractical, but I see no need to make it easy.
The short answer, I think, is that if you change an interface, you should reflect on what changes are needed in all the implemented classes, grit your teeth, and get on and make them.
you should always follow the principle of "Open for extension Close for modification"
if u add a new method the repercussions will be in all the Classes implementing it , U have to implement the method to all (be it java 5 or 8 until its a default method), so better
Create a new interface and the needful classes should extend it
we need to add a method to the interface
Well then there's no way around it. Without any context for what you're adding and why, I'll take your word for it that you do need to. Make sure that's actually the case.
Java 5: add the method. Fix all the classes implementing it.
You can consider adding a default to a new abstract base class which implements the interface, and make all implementations extend that. Then if you're in the same situation in the future you'll have an easier time.
Java 8: add a default method

Java - How to avoid static and default methods in interface

My question is rather theoretical:
Lets say I have Java 8 project using static and default methods in interfaces. I need to get rid of them because I am porting the code to Java 7 (lets say it is an Android app prior to Android N).
How to do that? I know there is Retrolambda plugin for that and I successfully use it. But I am thinking about "pure" solution done by altering the code. What are the options?
I know I can remove static and default methods from interface and put them into abstract class that implements this interface and then alter the code wherever there is reference to that interface (this is what Retrolambda does, if I understood the process correctly).
My teacher had indicated it can be done just by "suitable change in interface definition" without using additional class. But so far I failed in finding the solution. I tried putting implementations directly into target classes but that caused a series of troubles in my particular project.
Anyone have some idea or clue I am missing?
I think it is at first questionable that you actually used such a thing in your Java8 project. Interface should remain without implementations. Default methods were introduced mainly for APIs backward compatibility(if method has to be added to Interface from previous versions and you can't afford to force users of API to change their code and you don't like creating InterfaceV2). Not for "daily usage".
I think when porting, you should just export the methods to the static *Util classes. This way you can reuse it and you are not breaking the main principle of Interface.

why are interfaces created instead of their implementations for every class

It seems to be the standard so I have been going along with it so far, but now I am building a new class from scratch instead of modifying the old ones and feel I should understand why I should follow the projects convention.
Almost every class has an interface to it which is called classnameable. In the code database.class would never appear even once but in place where I would want to use that class I see databaseable.class.
To my understanding an interface was a class that was never implemented but was inhereted from to keep standards. So why are the interfaces being used as if they were real classes?
To my understanding an interface was a class that was never
implemented but was inhereted from to keep standards. So why are the
interfaces being used as if they were real classes.
This is a bit confused. An interface defines an API, so that pieces of code from different authors, modules or projects can interact. For example, java.util.Collections.sort() can sort anything that implements the List interface and contains objects that implement the Comparable interface - even though the implementation classes may not have existed yet when the sorting code was written!
Now the situation in your project seems to reflect an unfortunately rather common antipattern: having an interface for everything, mostly with a single implementation class, even for internal classes.
This used to be strongly promoted by proponents of Test-Driven-Development (TDD) who see it as vital to be able to test every class in isolation with all its dependencies replaced by mock objects. Older mocking frameworks could only mock interfaces, so to be able to test every class in isolation, all inter-class dependencies had to be through interfaces.
Fortunately, newer mocking frameworks can mock concrete classes and don't require you to pollute your project with unnecessary interfaces. Some people will probably still argue that it should be done anyway to "reduce coupling", but IMO they're just rationalizing their desire not to change their practices.
And of course, if you don't do fundamentalist TDD, there never was a good reason to have an interface for everything - but very good reasons to have interfaces for some things.
If you've got an interface for pretty much every single class in your project even though there's no reason for it, that's not a good thing and in this day and age there's no great reason for it. It may be a legacy from days gone by when it was required by some external testing toolkit for instance - but these days that's not a requirement.
It may be of course that someone's heard that loose coupling is a good thing, that you should always couple to interfaces and not concrete classes, and taken this idea to an extreme.
On the other hand, it is good practice to define interfaces for some classes even if there's only one of them (at the moment.) When I'm writing a class I try to think along the lines of whether another (potentially useful) implementation could exist, and if so I'll put an interface in. If it's not used it's no problem, but if it is it saves time and hassle and refactoring later.
If you want a class for your interfaces then a common way is to create an AbstractFoo class to go with the Foo interface. You can provide simple implementation of the required methods, allowing derived classes to overwrite them as needed. See AbstractCollection for an example of such a class.
The advantage is that you don't have to implement all the small stuff, it is already done for you. The disadvantage is that you can't inherit from any other class. You pays your money and you takes your choice.
A good indication for bad design is when you have a ISomething or a SomethingImpl. The interface name should state how to use it (i.e. List), the class name should state how it works (i.e. ArrayList).
If you need pre- or suffixes because the names would be the same, this means there is only one way to implement it, and then there is probably no need for a separation. (If you think there will be more sophisticated implementations in the future, name your class DefaultSomething or SimpleSomething)

How to test Java app operating directly on external API

After comming from Ruby world, I'm having little problems doing TDD in Java. The biggest issue is when I have application that is just communicating with external API.
Say I want to just fetch some data from Google Calendar, or 5 tweets from some Twitter user and display it.
In Ruby, I don't have any problems, because I can monkey-patch the API library in tests directly, but I have no such option in Java.
If I think about this in terms of MVC, my model objects are directly accessing the API through some library. The question is, is this bad design? Should I always wrap any API library in some interface, so I can mock/stub it in Java?
Because when I think about this, the only purpose of that interface would be to simulate (please don't kill me for saying this) the monkey-patch. Meaning that any time I use any external resource, I have to wrap each layer in interface that can be stubbed out.
# do I have to abstract everything just to do this in Java?
Twitter.stub!(:search)
Now you might say that I should always abstract away the interface, so I can change the underlying layer to anything else. But if I'm writing twitter app, I'm not going to change it to RSS reader.
Yes, I can add for example Facebook and then it would make sense to have interface. But when there is no other resource that can be substituted for the one I'm using, than I still have to wrap everything in interfaces to make it testable.
Am I missing something, or is this just a way to test in the Java world?
Using interfaces is just generally good practice in Java. Some languages have multiple inheritance, others have duck typing, Java has interfaces. It's a key feature of the language, it lets me use
different aspects of a class in different contexts and
different implementations of the same contract without changing client code.
So interfaces are a concept you should embrace in general, and then you would reap the benefits in situations like this where you could substitute your services by mock objects.
One of the most important books about Java best practices is Effective Java by Joshua Bloch. I would highly suggest you to read it. In this context the most important part is Item 52: Refer to objects by their interfaces. Quote:
More generally, you should favor the use of interfaces rather than
classes to refer to objects. If appropriate interface types exist, then parameters, return values, variables, and fields should all be declared using interface
types. The only time you really need to refer to an object’s class is when you’re
creating it with a constructor.
And if you take things even further (e.g. when using dependency injection), you aren't even calling the constructor.
One of the key problems of switching languages is that you have to switch the way of thinking too. You can't program language x effectively while thinking in language y. You can't program C effectively without using pointers, Ruby not without duck typing and Java not without Interfaces.
Wrapping the external API is the way I would do this.
So, as you already said, you would have an interface and two classes: the real one and the dummy implementation.
Yes, it may seem unreasonable from the perspective of some services indeed being specific, like Twitter. But, this way your build process doesn't depend on external resources. Depending on external libraries isn't all that bad, but having your tests depend on actual data present or not present out there on the web can mess up the build process.
The easiest way is to wrap the API service with your interface/class pair and use that throughout your code.
I understand that what you want are Mock objects.
As you described it, one of the ways one can generate "test versions" of objects is by implementing a common interface and using it.
However, what you are missing is to simply extend the class (provided that it is not declared final) and override the methods that you want to mock. (NB: the possibility of doing that is the reason why it is considered bad form for a library to declare its classes final - it can make testing considerably harder.)
There is a number of Java libraries that aim in facilitating the use of Mock objects - you can look at Mockito or EasyMock.
Mockito is more handy and like your ruby mocks.
You can "monkey-patch" an API in Java. The Java language itself does not provide specific means to do it, but the JVM and the standard libraries do. In Ruby, developers can use the Mocha library for that. In Java, you can use the JMockit library (which I created because of limitations in older mocking tools).
Here is an example JMockit test, equivalent to the test_should_calculate_value_of_unshipped_orders test available in Mocha documentation:
#Test
public void shouldCalculateValueOfUnshippedOrders()
{
final Order anOrder = new Order();
final List<Order> orders = asList(anOrder, new Order(), new Order());
new NonStrictExpectations(Order.class)
{{
Order.findAll(); result = orders;
anOrder.getTotalCost(); result = 10;
}};
assertEquals(30, Order.unshippedValue());
}

Where to put potentially re-useable helper functions?

This is language agnostic, but I'm working with Java currently.
I have a class Odp that does stuff. It has two private helper methods, one of which determines the max value in an int[][], and the other returns the occurrences of a character in a String.
These aren't directly related to the task at hand, and seem like they could be reused in future projects. Where is the best place to put this code?
Make it public -- bad, because Odp's functionality is not directly related, and these private methods are an implementation detail that don't need to be in the public interface.
Move them to a different class -- but what would this class be called? MiscFunctionsWithNoOtherHome? There's no unifying theme to them.
Leave it private and copy/paste into other classes if necessary -- BAD
What else could I do?
Here's one solution:
Move the method that determines te max value in a two-dimensional int array to a public class called IntUtils and put the class to a util package.
Put the method that returns the occurrences of a character in a String to a puclic class called StringUtils and put the class to a util package.
There's nothing particularly bad about writing static helper classes in Java. But make sure that you don't reinvent the wheel; the methods that you just described might already be in some OS library, like Jakarta Commons.
Wait until you need it!
Your classes wil be better for it, as you have no idea for now how your exact future needs will be.
When you are ready, in Eclipse "Extract Method".
EDIT: I have found that test driven development give code that is easier to reuse because you think of the API up front.
A lot of people create a Utility class with a lot of such methods declared as static. Some people don't like this approach but I think it strikes a balance between design, code reuse, and practicality.
If it were me, I'd either:
create one or more Helper classes that contained the methods as static publics, naming them as precisely as possible, or
if these methods are all going to be used by classes of basically the same type, I'd create an abstract base class that includes these as protected methods.
Most of the time I end up going with 1, although the helper methods I write are usually a little more specific than the ones you've mentioned, so it's easier to come up with a class name.
I not know what the other languages do but I have the voice of experience in Java on this: Just move to the end-brace of your class and write what you need ( or nested class if you prefer as that is accepted canonical convention in Java )
Move the file scope class ( default access class right there in the file ) to it's own compilation unit ( public class in it's own file ) when the compiler moans about it.
See other's comments about nested classes of same name if differing classes have the same functionality in nested class of same name. What will happen on larger code bases is the two will diverge over time and create maintainability issues that yield to Java's Name of class as type of class typing convention that forces you to resolve the issue somehow.
What else could I do?
Be careful not to yield to beginner impulses on this. Your 1-2 punch nails it, resist temptation.
In my experience, most large projects will have some files for "general" functions, which are usually all sorts of helper functions like this one which don't have any builtin language library.
In your case, I'd create a new folder (new package for Java) called "General", then create a file to group together functions (for Java, this will just be a class with lots of static members).
For example, in your case, I'd have something like: General/ArrayUtils.java, and in that I'd throw your function and any other function you need.
Don't worry that for now this is making a new class (and package) for only one function. Like you said in the question, this will be something you'll use for the next project, and the next. Over time, this "General" package will start to grow all sorts of really great helper classes, like MathUtils, StringUtils, etc. which you can easily copy to every project you work on.
You should avoid helper classes if you can, since it creates redundant dependencies. Instead, if the classes using the helper methods are of the same type (as kbrasee wrote), create an abstract superclass containing the methods.
If you do choose to make a separate class do consider making it package local, or at least the methods, since it may not make sense for smaller projects. If your helper methods are something you will use between projects, then a library-like approach is the nicest to code in, as mentioned by Edan Maor.
You could make a separate project called utils or something, where you add the classes needed, and attach them as a library to the project you are working on. Then you can easily make inter-project library updates/fixes by one modification. You could make a package for these tools, even though they may not be that unified (java.util anyone?).
Option 2 is probably your best bet in Java, despite being unsatisfying. Java is unsatisfying, so no surprise there.
Another option might be to use the C Preprocessor as a part of your build process. You could put some private static functions into file with no class, and then include that file somewhere inside a class you want to use it in. This may have an effect on the size of your class files if you go overboard with it, of course.

Categories