我正在为以下类@Component类编写Junit测试用例。我实际上是在为原始应用程序使用Sql Server。但是,作为测试的一部分,我在内存h2 db中使用了。我想在不启动原始应用程序的情况下测试此类如果在测试类中使用存储库,我可以看到测试中返回的数据,但是恰好是当我调用@Component类中的void方法获取NULL指针时。
这是我的代码。

    @Component
    public class CandidatesTableServiceImpl {



        @Autowired
        private CandidatesTableRepository candidatesTableRepository;

        @Transactional
        public void getAllRecordsFromCandidateTable() throws ParseException {

            List<CandidatesTable> customerRecord = candidatesTableRepository
                    .findByStatus(status);

/** This method throwing Null pointer exception when calling from method **/


    }


我的src / test / reources / application.properties

spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=sa
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
# Create DDL
spring.jpa.hibernate.ddl-auto=create


我的Test类看起来像这样

@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(connection = EmbeddedDatabaseConnection.H2)
@Transactional
public class CandidateTableTest {

    @Autowired
    TestEntityManager entityManager;

    @Autowired
    CandidatesTableRepository candidatesTableRepository;

    String status;

    @Before
    public void init() {
        CandidatesTableServiceImpl candidatesTableServiceImpl= new candidatesTableServiceImpl()

    }

    @Test
    public void checkSaveMethod() throws ParseException {

        CandidatesTable candidatesTable = new CandidatesTable();

        candidatesTable.setStatus(status);
        candidatesTable.setCandidatesTableID(1);
        candidatesTable.setAccountNumber("2000321654");

        candidatesTableRepository.save(candidatesTable);
        this.entityManager.persist(candidatesTable);


/** This method works fine **/
                  List<CandidatesTable> alertRecord = candidatesTableRepository.findByStatus(status);


/** This method throwing NUll Pointer excption **/
        candidatesTableServiceImpl.getAllRecordsFromCandidateTable();

    }

}

最佳答案

您没有指定扫描组件的位置,使用

@ComponentScan(value = ["your.package.name"])


您还需要刷新数据

   @Test
   public void checkSaveMethod() throws ParseException {

       CandidatesTable candidatesTable = new CandidatesTable();

       candidatesTable.setStatus(status);
       candidatesTable.setCandidatesTableID(1);
       candidatesTable.setAccountNumber("2000321654");

       candidatesTableRepository.save(candidatesTable);
       this.entityManager.persist(candidatesTable);
       this.entityManager.flush();

/** This method works fine **/
                 List<CandidatesTable> alertRecord = candidatesTableRepository.findByStatus(status);


/** This method throwing NUll Pointer excption **/
       candidatesTableServiceImpl.getAllRecordsFromCandidateTable();

   }

09-28 07:11