Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing JUnit data between tests

Tags:

java

junit

I just discovered when creating some CRUD tests that you can't set data in one test and have it read in another test (data is set back to its initialization between each test).

All I'm trying to do is (C)reate an object with one test, and (R)ead it with the next. Does JUnit have a way to do this, or is it ideologically coded such that tests are not allowed to depend on each other?

like image 348
orbfish Avatar asked Jun 29 '10 21:06

orbfish


People also ask

Does JUnit creates a new instance for each test?

JUnit creates a new instance of the test class before invoking each @Test method. This helps provide independence between test methods and avoids unintentional side effects in the test code. Because each test method runs on a new test class instance, we can't reuse instance variable values across test methods.

How do you run the same test case multiple times in JUnit?

The easiest (as in least amount of new code required) way to do this is to run the test as a parametrized test (annotate with an @RunWith(Parameterized. class) and add a method to provide 10 empty parameters). That way the framework will run the test 10 times.


Video Answer


2 Answers

Well, for unit tests your aim should be to test the smallest isolated piece of code, usually method by method. So testCreate() is a test case and testRead() is another. However, there is nothing that stops you from creating a testCreateAndRead() to test the two functions together. But then if the test fails, which code unit does the test fail at? You don't know. Those kind of tests are more like integration test, which should be treated differently.

If you really want to do it, you can create a static class variable to store the object created by testCreate(), then use it in testRead().

As I have no idea what version of Junit you talking about, I just pick up the ancient one Junit 3.8:

Utterly ugly but works:

public class Test extends TestCase{      static String stuff;      public void testCreate(){         stuff = "abc";     }      public void testRead(){         assertEquals(stuff, "abc");     } } 
like image 153
Jason Wang Avatar answered Sep 18 '22 13:09

Jason Wang


JUnit promotes independent tests. One option would be to put the two logical tests into one @Test method.

TestNG was partly created to allow these kinds of dependencies among tests. It enforces local declarations of test dependencies -- it runs tests in a valid order, and does not run tests that depend on a failed test. See http://testng.org/doc/documentation-main.html#dependent-methods for examples.

like image 28
Andy Thomas Avatar answered Sep 19 '22 13:09

Andy Thomas