#@Autowired question for spring boot tests

3 messages · Page 1 of 1 (latest)

bleak knoll
#

My employeeRepository remains being a null value for this test:

@SpringBootTest
public class EmployeeTest {

    @Autowired
    private EmployeeRepository employeeRepository;


    @AfterEach
    public void tearDown() {
        employeeRepository.deleteAll();
    }

    @Test
    public void testCannotCreateTwoCEOs() {
        Employee manager = new Employee();
        manager.setFirstName("John");
        manager.setLastName("Doe");
        manager.setSalary(15000);
        manager.setIsManager(true);
        manager.setIsCEO(false);

        Employee savedManager = employeeRepository.save(manager);

        Employee ceo1 = new Employee();
        ceo1.setFirstName("Jane");
        ceo1.setLastName("Doe");
        ceo1.setSalary(20000);
        ceo1.setIsManager(false);
        ceo1.setIsCEO(true);
        ceo1.setManagerId(savedManager.getId());

        Employee savedCEO1 = employeeRepository.save(ceo1);

        // Attempt to create another CEO with the same manager ID
        Employee ceo2 = new Employee();
        ceo2.setFirstName("Alice");
        ceo2.setLastName("Smith");
        ceo2.setSalary(30000);
        ceo2.setIsManager(false);
        ceo2.setIsCEO(true);
        ceo2.setManagerId(savedManager.getId());

        assertThrows(DataIntegrityViolationException.class, () -> employeeRepository.save(ceo2));
    }
java.lang.NullPointerException: Cannot invoke "com.xxx.xxx.employees.EmployeeRepository.checkIfDBContainsCEO()" because "this.employeeRepository" is null

This is the EmployeeRepository:


@Repository
public interface EmployeeRepository extends MongoRepository<Employee, ObjectId> {
    @Query("{'isCEO': true}")
    boolean checkIfDBContainsCEO();
}
worn mangoBOT
#

This post has been reserved for your question.

Hey @bleak knoll! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.