gpt4 book ai didi

java - 如何在java中使用注释相关参数检查自定义运行时异常属性

转载 作者:太空宇宙 更新时间:2023-11-04 10:08:07 25 4
gpt4 key购买 nike

这是我的类结构

public class OrderRuntimeException extends RuntimeException
{
private final Field field;

public OrderManagementServiceRuntimeException(String messege, MyError myError)
{
super(messege);
this.field = field;
}

}

public Class MyError{

String name;
Sttring description;

public MyError(String name, String description){

this.name = name;
this.description = description;
}
}

public void getOrders(Order order){
.......
throw new OrderRuntimeException("Invalid Order",new MyError("Illegale","this is an illegal..."))
}

我想用 Junit 测试这个异常和 MeError 类型对象(名称和描述)。我写了这个

public class MyTest {

@Rule
public ExpectedException thrown = ExpectedException.none();


@Test(expectedExceptions = OrderRuntimeException.class, expectedExceptionsMessageRegExp = "Invalid Order")
public void testSetRequestTime_invalidRequestDTOImplType()
{

thrown.expect(......);

}

}

我使用 @Rule .. 来获取 throwed.expect() 功能。但我无法从此测试中获取 MyError 类型对象。如果有人对解决方案有想法,请发表评论或回答。

最佳答案

我认为你可以使用org.hamcrest.Matchers来做出这种类型的断言。

expectedException.expect(OrderRuntimeException.class);
expectedException.expect(org.hamcrest.Matchers.hasProperty("myError", allOf(
org.hamcrest.Matchers.hasProperty("name", is("exampleName")),
org.hamcrest.Matchers.hasProperty("description", is("exampleDescription"))
)));

关于java - 如何在java中使用注释相关参数检查自定义运行时异常属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52685338/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com