繁体   English   中英

测试Remote接口的所有方法是否抛出RemoteException

[英]Test if all methods of a Remote interface throw RemoteException

使用RMI(远程方法调用)时,扩展Remote接口中定义的所有方法都必须在其throws子句中包含RemoteException

例如,请参阅此RMI教程中的以下“ 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构建将成功结束,这表明该条件未经过测试。

我看到了一个写自定义测试的解决方案,该解决方案将查看每个Remote接口,并使用反射检查每个方法是否抛出RemoteException 但是我相信有更好的方法。

rmic检查它。 您可以将rmic合并到您的构建中。 如果要使用动态存根,请确保随后删除_stub.class文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM