0

I'm having some troubles with testing in Android. For each test I do, I have a common set of instructions to do before the test and after the test. So, the idea would be define a setUp() and tearDown() method.

So far so good. The problem is that, apparently, the tearDown() method is not invoked when the test "fails" (that means when the tests throws an Exception).

Is there a method that can be invoked when a test throws an Exception or a "tricky" way to do this?

Marco10
  • 87
  • 2
  • 8

1 Answers1

2

Test like this:

try{
    setUp();
    /* do some testing*/
}catch(Exception ex){
    /* do something with the exception */
    /* let the test fail */
}finally{
    tearDown();
}

It's probably the easiest solution for your problem, but from the viewpoint of good design practice this should be avoided.

edit:

There are annotations in jUnit: Different teardown for each @Test in jUnit

edit2:

The setUp() method is invoked before every test. You use it to initialize variables and clean up from previous tests. You can also use the JUnit tearDown() method, which runs after every test method. The tutorial does not use it.

http://developer.android.com/tools/testing/activity_test.html

If you have different tearDown() Methods for each test, I think you need to change them.

Community
  • 1
  • 1
seb
  • 4,279
  • 2
  • 25
  • 36
  • _ahem [coughs] ahem_? – Hungry Blue Dev May 13 '14 at 15:17
  • Like I said to #ambigram_maker, I don't want to alter the tests. I want to know if there's a way to defie somehow that when a test (generically) fails, a method is invoked. Is there a way to do it? – Marco10 May 13 '14 at 15:21
  • Well... since the `tearDown()` method is invoked after every test, I'm not using any annotation. But is there an annotation I can use for my problem? – Marco10 May 13 '14 at 15:32
  • If you don't want to change anything in the tests, make the `tearDown()` method work so that it's invariant if you call it more than once. Add and `After`- or `AfterClass`-Annotation to the Tests and it should be ok. – seb May 13 '14 at 15:36
  • For some reason I can't use the `@After` ou `@AfterClass` annotations. My project doesn't recognize it. I tried to add jUnit library to the classpath, but still nothing. Any idea? – Marco10 May 13 '14 at 15:55