JUnit4 tests are passed separately, and when you run the entire file with tests, some of them fail



  • I am new to programming. I Wrote several unit tests. Separately, they all pass. But when running the entire file, errors appear for some of them, for example:

    There is a test

    @ org.junit.Test
    public void getTitle () {
        Deanery dekanat = new Deanery ();
        Group.addGroup ("testTitle");
        assertEquals ("testTitle", Deanery.groupList.get (0) .getTitle ());
    }
    

    A new group of students named "testTitle" is created in the ArrayList "groupList". In the test, I compare the group name obtained from the getter with a string.

    When running the entire file with tests, it produces the following:

    org.junit.ComparisonFailure:
    Expected: testTitle
    Actual: testGroup
    

    Moreover, in this test there is no name "testGroup" at all (but in other tests it does). It seems that JUnit does not clear the data when moving from test to test. When run in debug mode, this is how it happens.

    What could be the reason for this behavior and how to fix it? Or what am I doing wrong? Thanks anyway!



  • Usually static variables live until the program that loaded the class with this static ends. The static is initialized once, when the class is loaded by the class loader. "Usually" I wrote it because it is possible to change this behavior by rewriting the loader class, as is done, for example, in OSGI implementations

    I suppose your tests change the value of a static variable, and you expect that the value of these fields will be "as at the start of the program", but this is not the case, the values ​​from the previous runs of the tests are saved in them. all tests are run within one jvm run

    PS: With your tests there are 2 ways, either you manually initialize the statics as needed before starting each test, or you get rid of it and problems with it.



Suggested Topics