Resetting static fields for JUnit tests

后端 未结 3 430
迷失自我
迷失自我 2021-01-11 15:25

I have a set of JUnit tests which call the main method on a Java program, passes in args and checks the output. That\'s fine.

However, if the program I am testing ha

3条回答
  •  迷失自我
    2021-01-11 16:10

    Take a look at this post: Set Private Static Field. Unlike BeanInject or ReflectionTestUtils (which I use a lot), this mechanism does not require a instance of the class. Since this is a static field I wasn't sure if you had an instance. If you do, use one of the two above.

    Copied from post:

     public static void main(String[] args) throws Exception
    {
        Field field = MyClass.class.getDeclaredField("woot");
        field.setAccessible(true);
        field.set(null, "New value");
    }
    

    I was surprised to see that ReflectionTestUtils required an instance. Seems like it should be able to handle this case. Too bad.

    As others have stated, do this in the @Before method to ensure state BEFORE your test begins. Doing so in the @After is error prone as it assumes that you other test might affect the state of the static field.

提交回复
热议问题