首页 > 解决方案 > Java-一个类有一个注解,如何在没有该注解的情况下测试这个类

问题描述

示例:

1 @Schema // you don't need to care what Schema annotation is
2 public class A {
3     public Schema getSchema() {
4         Schema schema = getClass().getAnnotation(Schema.class);
5         if (schema == null) {
6             throw new IllegalStateException("Schema annotation is missing for class " + getClass().getName());
7         }
8         return schema;
9     }
10 }

如何编写可以覆盖第 6 行的单元测试。现在我只能覆盖第 4、5、8 行

标签: javaunit-testingannotations

解决方案


只有当有扩展的子类时,您的方案才有意义class A。因此,要对其进行测试,您可以创建一个子类并对其进行测试。

@Test(expected = IllegalStateException.class)
public void getSchema() {
    A testClass = new A() {};
    testClass.getSchema();
}

推荐阅读