Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Beans are not Autowired during tests (java.lang.NullPointerException)

my application normally works fine, but when I run tests, or build application by maven, application is shutting down due tests with errors java.lang.NullPointerException. I debugged it and find out my that my beans in service layer are not Autowired and they are null. Here is my class with tests:

public class CompanyServiceSimpleTest {
    private CompanyService companyService;

    @Before
    public void setUp() {
        companyService = new CompanyServiceImpl();
    }

    // Here is sample test
    @Test
    public void testNumberOfCompanies() {
        Assert.assertEquals(2, companyService.findAll().size());
    }
}

companyService is initialized, but beans in it not. Here is CompanyServiceImpl:

@Service
public class CompanyServiceImpl implements CompanyService {

    @Autowired
    private CompanyRepository companyRepository; // is null

    @Autowired
    private NotificationService notificationService; // is null

    @Override
    public List<CompanyDto> findAll() {
        List<CompanyEntity> entities = companyRepository.find(0, Integer.MAX_VALUE);
        return entities.stream().map(Translations.COMPANY_DOMAIN_TO_DTO).collect(Collectors.toList());
    }
    // ... some other functions
}

So when is called companyRepository.find() applications crashes. Here is repository class:

@Repository
@Profile("inMemory")
public class CompanyInMemoryRepository implements CompanyRepository {

    private final List<CompanyEntity> DATA = new ArrayList<>();
    private AtomicLong idGenerator = new AtomicLong(3);

    @Override
    public List<CompanyEntity> find(int offset, int limit) {
        return DATA.subList(offset, Math.min(offset+limit, DATA.size()));
    }
    // ... some others functions
}

I have set up profile for that service but I had that VM options in Idea:

-Dspring.profiles.active=develpment,inMemory

So it should works.

like image 758
Denis Stephanov Avatar asked Nov 08 '22 14:11

Denis Stephanov


1 Answers

To make autowiring work it has to be a Spring integration test. You have to anotate your test class with:

@RunWith(SpringJUnit4ClassRunner.class) and @ContextConfiguration(classes = {MyApplicationConfig.class})

If it is a Spring Boot app e.g.:

@RunWith(SpringJUnit4ClassRunner.class) and @SpringBootTest(classes = {MyApp.class, MyApplicationConfig.class}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)

More on this topic: http://www.baeldung.com/integration-testing-in-spring and http://www.baeldung.com/spring-boot-testing

like image 53
Pawel Os. Avatar answered Nov 14 '22 22:11

Pawel Os.