如何编写具有Spring存储库代码的@Component类的Integration Test?

时间:2019-02-16 23:31:50

标签: java spring spring-boot junit spring-data-jpa

我正在为下面的@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();

    }

}

1 个答案:

答案 0 :(得分:0)

您未指定在何处扫描组件,请使用

@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();

   }