The-Higgs-Boson
The-Higgs-Boson

Reputation: 91

PostConstruct not being called in junits

When i am testing(JUnit) this class i get NullPointerException when i call getdata method

private static final Map<String, Function<String, String>> REFERENCE_MAP = new HashMap<>();

@Autowired
private static classA aobj;

@PostConstruct
public void initialize() {
    REFERENCE_MAP.put("s1", (bucketName) -> {
         return aobj.getSomething1(bucketName);
    });
    REFERENCE_MAP.put("s2", (bucketName) -> {
        return aobj.getSomething2(bucketName);
    });
    REFERENCE_MAP.put("s3", (bucketName) -> {
        return aobj.getSomething3(bucketName);
    });
    REFERENCE_MAP.put("s4", (bucketName) -> {
        return aobj.getSomething4(bucketName);
    });
}
public String getdata() {
    return REFERENCE_MAP.get("s1").apply("bucketname1");
}

how do i solve the problem

Upvotes: 2

Views: 6101

Answers (1)

The-Higgs-Boson
The-Higgs-Boson

Reputation: 91

In test file call the initialize method before running tests

@RunWith(MockitoJUnitRunner.class)
public class testClass {

    @InjectMocks
    private mainClass mainclass;

    @Mock
    private ClassA obja;

    @Before
    public void init() {
        mainclass.initialize();

    }
}

Upvotes: 3

Related Questions