我的代码中有这样的情况:
抽象异常
@Path("/v1/example")
@Produces("application/json")
@Consumes("application/json")
public class HelloWorldResource {
@EJB
HelloWorldRemote helloWorldRemote;
@GET
@Path("/hello")
public Response getSayHello(){
String helloText = helloWorldRemote.sayHello();
final Response response = Response.ok(helloText).build();
return response;
}
public String nonRESTSayHello(){
return "SAY HELLO NONREST";
}
}
由3个具体例外实现
@RunWith(Arquillian.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class HelloWorldResourceTest {
@Test
@OperateOnDeployment("REST")
public void testGetSayHello() {
System.out.println("testGETSAYHELLO!!!!!");
Client client = ClientBuilder.newClient();
Invocation.Builder builder = client.target(
"http://localhost:8080/CoverageTest/api/v1/example/hello")
.request(MediaType.APPLICATION_JSON_TYPE);
javax.ws.rs.core.Response response = builder.get();
assertEquals(200, response.getStatus());
}
/*
* @Test
* public void testNonRESTSayHello(){
* HelloWorldResource hwr=new HelloWorldResource();
* String str = hwr.nonRESTSayHello();
* assertEquals("SAY HELLO NONREST",str);
* }
*/
}
返回抽象异常实例的方法:
public abstract class AbstractException extends Exception {
...
}
然后在我的代码中,我有一个处理抛出异常的方法:
public class ConcreteException1 extends AbstractException {
// ...
}
public class ConcreteException2 extends AbstractException {
// ...
}
public class ConcreteException3 extends AbstractException {
// ...
}
此代码无法编译,因为存在"未处理的异常类型AbstractException"。
为了使编译我必须这样做:
public AbstractException createException()
{
// create an exception that can be one of the 3 concrete class
}
我觉得维护起来很容易,有没有更好的方法呢?
感谢您的回答!
答案 0 :(得分:0)
您可以尝试以下方法:
public void handleThrowing() throws AbstractException {
//...
throw createException();
}