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?

6
  • try{...} catch (...) {...}? Commented May 13, 2014 at 15:10
  • But I want it to work like the tearDown() method. Using try{...} catch (...) {...} makes me write the code for every test, and I don't want that. Commented May 13, 2014 at 15:18
  • Sorry dude... better safe than sorry, and BTW, what harm is a little copy-paste gonna do? Commented May 13, 2014 at 15:20
  • But I have almost 200 tests, and I'me using an instrumentation tool to automatically generate the tearDown() and setUp() methods Commented May 13, 2014 at 15:22
  • Okay... that's a bigger prob than I expected... Commented May 13, 2014 at 15:25

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

ahem [coughs] ahem?
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?
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?
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.
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?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.