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

时间:2016-01-15 09:45:32

标签: java testing reflection junit

我希望只有在给出注释的情况下才运行集成测试。问题是测试用例需要一些需要在@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());
}

DEV注释:

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

1 个答案:

答案 0 :(得分:1)

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

您应该分三个阶段分别执行测试:之前,测试和之后。迭代Test-methods,找到Before-and-method方法并按所需顺序执行它们。

伪代码:

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);
}