0

Example code:

public class Count {
    static int count;

    public static int add() {
       return ++count;
    } 
}

I want test1 and test2 run totally separately so that they both pass. How can I finish that? My IDE is Intellij IDEA.


public class CountTest {
    @Test
    public void test1() throws Exception {
        Count.add();
        assertEquals(1, Count.count);//pass.Now count=1
    }

    @Test
    public void test2() throws Exception {
        Count.add();
        assertEquals(1, Count.count);//error, now the count=2
    }
}

Assume the test1 runs before test2.

This is just a simplified code. In fact the code is more complex so I can't just make count=0 in @after method.

guo
  • 9,674
  • 9
  • 41
  • 79
  • 2
    But what is the target of that? Basically you are testing static method, so there is no instance of particular object on heap. My suggestion is to refactor your code to not use **static** methods. Other solution is using `@Before` annotation and reset all needed values there. – jakubbialkowski Jul 30 '16 at 13:49

2 Answers2

2

There is no automated way of resetting all the static variables in a class. This is one reason why you should refactor your code to stop using statics.

Your options are:

  1. Refactor your code
  2. Use the @Before annotation. This can be a problem if you've got lots of variables. Whilst its boring code to write, if you forget to reset one of the variables, one of your tests will fail so at least you'll get chance to fix it.
  3. Use reflection to dynamically find all the member of your class and reset them.
  4. Reload the class via the class loader.
  5. Refactor you class. (I know I've mentioned it before but its so important I thought it was worth mentioning again)

3 and 4 are a lot of work for not much gain. Any solution apart from refactoring will still give you problems if you start trying to run your tests in parallel.

matt helliwell
  • 2,574
  • 16
  • 24
1

Use the @Before annotation to re-initialize your variable before each test :

@Before
public void resetCount(){
    Count.count = 0;
}
Jean-François Savard
  • 20,626
  • 7
  • 49
  • 76
  • What if I have so many things like `Count.count`? Is there any better way to provide a clean-up environment? – guo Jul 30 '16 at 13:51
  • @guo Just clean up everything you want in the method annotated with Before. If you do, don't forget to chose another name than resetCount. – Jean-François Savard Jul 30 '16 at 13:52