如何使用给定的自定义注释运行测试用例



我想仅在它提供了注释时才运行集成测试。问题是测试用例需要一些变量,这些变量需要在 @Before 中初始化并在 @After 中销毁。

我编写了执行已给出注释的测试的代码,但由于需要在@Before阶段初始化变量,它们都失败了。

我首先调用@Before阶段(我假设变量已初始化),然后运行测试方法,然后调用@After阶段。但是我在测试方法上得到了NullPointerException

如何初始化测试方法的变量?调用@Before阶段还不够吗?

我拥有的代码:

public static void main(String[] args) throws Exception {
    Class<TodoMapperTest> obj = TodoMapperTest.class;
    int passed = 0;
    int failed = 0;
    int count = 0;
    for (Method method : obj.getDeclaredMethods()) {
      if (method.isAnnotationPresent(Before.class))
        method.invoke(obj.newInstance());
      if (method.isAnnotationPresent(DEV.class)) {
        try {
          method.invoke(obj.newInstance());
          System.out.printf("%s - Test '%s' - passed %n", ++count, method.getName());
          passed++;
        } catch (Throwable ex) {
          System.out.printf("%s - Test '%s' - failed: %s %n", ++count, method.getName(), ex);
          failed++;
        }
      }
      if (method.isAnnotationPresent(After.class))
        method.invoke(obj.newInstance());
    }
    System.out.printf("%nResult : Total : %d, Passed: %d, Failed %d%n", count, passed, failed);
  }

@Before阶段:

TodoQueryMapper mapper;
SqlSession session;
@Before
  public void setUp() throws Exception {
    InputStream inputStream = Resources.getResourceAsStream("todo-mybatis/mybatis-test.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    inputStream.close();
    session = sqlSessionFactory.openSession();
    mapper = session.getMapper(TodoQueryMapper.class);
  }

编辑:测试用例:

@Test
@DEV
public void test_case() throws Exception {
  SqlParams params = new SqlParams();
  params.idList = Collections.singletonList(1234567);
  // In here, 'mapper' variable is null, even @Before invoked
  List<TodoDto> data = mapper.findByIdList(params); 
  assertEquals(1, data.size());
}

开发注释:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface DEV {
}

每次通过反射调用方法时,都会创建测试类的新实例:method.invoke(obj.newInstance());

应将测试执行分为三个阶段:之前、测试和之后。遍历测试方法,找到 Before- 和 After-方法并按所需顺序执行它们。

伪代码:

Class<AccountDaoMapperTest> objClass = AccountDaoMapperTest.class;
for (Method testMethod : findTestMethods(objClass)) {
    AccountDaoMapperTest objUnderTest = objClass.newInstance();
    findBeforeMethod(objClass).invoke(objUnderTest);
    testMethod.invoke(objUnderTest);
    findAfterMethod(objClass).invoke(objUnderTest);
}

最新更新