【发布时间】:2016-12-11 15:43:21
【问题描述】:
使用 RMI(远程方法调用)时,在扩展 Remote 的接口中定义的所有方法都需要在其 throws 子句中包含 RemoteException。
例如,从this RMI tutorial看下面的Computing接口。
public interface Compute extends Remote {
<T> T executeTask(Task<T> t) throws RemoteException;
}
问题是编译器不检查方法是否定义正确,而是在执行过程中当程序遇到Remote接口中的方法不抛出RemoteException时抛出异常。
如果在程序实际运行之前发现这些问题会更好。如何为这种情况编写测试?
编辑:我添加了一个示例代码来演示这个问题。
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>test</groupId>
<artifactId>test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.codehaus.mojo</groupId>
<artifactId>rmic-maven-plugin</artifactId>
<version>1.2.1</version>
</dependency>
</dependencies>
</project>
src/main/java/test/RemoteExample.java
package test;
import java.rmi.Remote;
public interface RemoteExample extends Remote {
// the method does not throw RemoteException
void action();
}
src/test/java/test/RemoteExampleTest.java
package test;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import org.junit.Test;
public class RemoteExampleTest {
@Test
public void test1() throws RemoteException {
RemoteExample example = new RemoteExample() {
public void action() {
// do nothing
}
};
// this fails
RemoteExample exported = (RemoteExample) UnicastRemoteObject.exportObject(example, 0);
}
}
mvn test 失败,因为RemoteExample.action() 方法在Remote 接口中声明但没有抛出RemoteException,因此无法导出。但是,如果在测试前加上@Ignore,maven build 会成功结束,这意味着条件没有经过测试。
我看到了一种编写自定义测试的解决方案,该测试将查看每个Remote 接口,并使用反射检查每个方法是否抛出RemoteException。但我相信有更好的方法。
【问题讨论】:
标签: java reflection junit rmi remoteexception