Search code examples
springspring-bootspring-mvcjunitjunit4

Nullpointer when testing components in springBoot 2


I have a SpringBoot 2 app with this component

@Component
@Slf4j
public class RequestHostelUtils {

    private RequestHostelUtils() {
        // Private constructor to hide the implicit public one
    }

and this other one

@Component
public class RequestEntityPredicates {

    private final RequestHostelUtils requestHostelUtils;

    public RequestEntityPredicates(RequestHostelUtils requestHostelUtils) {
        this.requestHostelUtils = requestHostelUtils;
    }

and this Unit Test, that when I test it I git a nullpointer in requestEntityPredicates because requestHostelUtils is null;

@RunWith(MockitoJUnitRunner.class)
@Slf4j
    public class RequestEntityValidatorsTests {

        @Autowired
        private RequestHostelUtils requestHostelUtils;

        private RequestEntityPredicates requestEntityPredicates;



    @Before
    public void setUp() throws Exception {
        requestEntityPredicates = new RequestEntityPredicates(requestHostelUtils);
    }

I also tried

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = { Application.class })
@Slf4j
 public class RequestEntityValidatorsTests {

with the same results


Solution

  • Load your beans into Spring:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(classes = { RequestHostelUtils.class, RequestEntityPredicates.class })
    @Slf4j
    public class RequestEntityValidatorsTests {