From the javadoc for the @Override annotation:
Indicates that a method declaration is
intended to override a method
declaration in a superclass. If a
method is annotated with this
annotation type but does not override
a superclass method, compilers are
required to generate an error message.
I've tended to use the @Override annotation in testing, when I want to test a specific method of a type and replace the behaviour of some other method called by my test subject. One of my colleagues is firmly of the opinion that this is not a valid use but is not sure why. Can anyone suggest why it is to be avoided?
I've added an example below to illustrate my usage.
For the test subject Foo:
public class Foo {
/**
* params set elsewhere
*/
private Map params;
public String doExecute(Map params) {
// TODO Auto-generated method stub
return null;
}
public String execute() {
return doExecute(params);
}
}
I would define a test like this:
public void testDoExecute() {
final Map expectedParams = new HashMap();
final String expectedResult= "expectedResult";
Foo foo = new Foo() {
@Override
public String doExecute(Map params) {
assertEquals(expectedParams, params);
return expectedResult;
}
};
assertEquals(expectedResult, foo.execute());
}
Then if my doExecute() signature changes I'll get a compile error on my test, rather than a confusing execution failure.
解决方案
Using the Override annotation in that kind of tests is perfectly valid, but the annotation has no specific relationship to testing at all; It can (and should) be used all over production code as well.