1

Here is my class

package com.myCompany.test;

// imports

@Test
public class Test{
    private static final Map<Type, String> depMap;
    static {
        depMap = new HashMap<>();
        depMap.put(Type.ONE, "1234");
    }

    @Test(groups="small")
    public void testOne(){
        // something
        String typeOneVal = depMap.get(Type.ONE); // NullPointerException
        // assertions
    }
}

The test suite looks like below:

<test name="Small Test Set">
    <groups>
        <run>
            <exclude name="brokenTests" />
            <include name="small" />
        </run>
    </groups>
    
    <packages>
        <package name="com.myCompany.test.*" />
    </packages>
</test>

How can depMap ever be null when this TestNG class is executed by method, class, suite etc? It runs on my local fine but fails in CI job, both executing the test suite. Pretty confused now!

xploreraj
  • 3,792
  • 12
  • 33
  • 51

1 Answers1

0

You should consider changing the static block to an @BeforeClass method. This will ensure that it works using the tools provided by the testing framework.

@BeforeClass
public void init() {
    depMap = new HashMap<>();
    depMap.put(Type.ONE, "1234");
}

This seems similar in terms of the core issue of the static initializer: Static initializer doesn't run during JUnit tests

Testing frameworks sometimes use reflection and other tools to optimize unit test execution which can cause errors like you're seeing. Without knowing more about your toolchain it is tough to say exactly what would cause the issue.

Joe W
  • 2,773
  • 15
  • 35