vendredi 15 janvier 2016

How to run test cases with given custom annotation

I want to run integration tests only if it has given annotation. The thing is that test cases need some variables which are needed to be initialized in @Before and destroyed in @After.

I wrote the code which executes the tests which have given annotation, but they all fail because of the variables which need to be initialized in @Before phase.

I first invoke @Before phase(I suppose the variables are initialized), then run the test method, then invoke @After phase. But I get NullPointerException in test method.

How to initialize variable for the test methods?? Isn't enough to invoke @Before phase??

The code I have:

public static void main(String[] args) throws Exception {
    Class<AccountDaoMapperTest> obj = AccountDaoMapperTest.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 phase:

AccountDaoQueryMapper mapper;
SqlSession session;

@Before
  public void setUp() throws Exception {
    InputStream inputStream = Resources.getResourceAsStream("account-mybatis/mybatis-test.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    inputStream.close();

    session = sqlSessionFactory.openSession();
    mapper = session.getMapper(AccountDaoQueryMapper.class);
  }

Edit: Test case:

@Test
@DEV
public void test_case() throws Exception {
  SqlParams params = new SqlParams();
  params.customerNo = 1234567;

  // In here, 'mapper' variable is null, even @Before invoked
  List<AccountDaoDto> data = mapper.findAccountInfoByCustomer(params); 

  assertEquals(2, data.size());
}





Aucun commentaire:

Enregistrer un commentaire