在java中覆盖,当使用@覆盖在java中

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值