2017-07-31 104 views
0

我在Service類中有一個簡單的getEmployeeList方法,它使用Spring JDBC來查詢數據庫以獲取僱員列表。java.lang.NullPointerException:無法在空對象上調用方法queryForList()

class EmployeeListService 
{ 

private static final String QUERY_FOR_GETTING_ALL_EMPLOYEE_LIST="select ID, name from emp order by name"; 

    def dataSource 
     private JdbcTemplate jdbcTemplate 

    @PostConstruct 
    def init() { 
      jdbcTemplate = new JdbcTemplate(dataSource) 
    } 


    def getEmployeeList() { 

     ArrayList<String> employeeList = jdbcTemplate.queryForList(QUERY_FOR_GETTING_ALL_EMPLOYEE_LIST); 
     return employeeList; 
    } 
} 

我正在爲getEmployeeList方法的Null檢查編寫一個Grails單元測試。

@WithGMock 
class EmployeeListServiceTest extends GrailsUnitTestCase { 

    EmployeeListService empService; 

    @Before 
    public void setUp() { 
     empService = new EmployeeListService(); 

    } 

    @Test 
    public void toCheckgetEmployeeListDoesNotReturnNull() 
    { 
     ArrayList<String> employeeList = empService.getEmployeeList() 

     assertNotNull(employeeList); 
    } 
} 

當我以正常流程執行程序時,我得到員工列表。但是,當我執行單元測試,我在單元測試中獲得異常

Failure: toCheckgetEmployeeListDoesNotReturnNull(com.employee.home.service.EmployeeListServiceTest) 

    java.lang.NullPointerException: Cannot invoke method queryForList() on null object 
     at com.employee.home.service.EmployeeListService.getEmployeeList(EmployeeListService.groovy:170) 
     at com.employee.home.service.EmployeeListServiceTest.toCheckgetEmployeeListDoesNotReturnNull(EmployeeListServiceTest.groovy:24) 
+0

所以,你的JdbcTemplate爲空。 – Tavo

+0

它只是表示jdbcTemplate爲空。這是依賴性問題!你在哪裏創建jdbcTemplate對象? –

+0

儘管我沒有提到jdbcTemplate和數據源,實際上我已經在服務類中創建了它們,例如EmployeeListService,理想情況下它不應該返回null – TechLife

回答

0

以下時,您手動創建安裝程序的方法爲您服務的情況下,postConstruct方法將不會被調用。

所以下面沒有被調用。

@PostConstruct 
    def init() { 
      jdbcTemplate = new JdbcTemplate(dataSource) 
    } 

這會導致您的JdbcTemplate在單元測試期間爲空。

我會建議你使用集成測試,如果你需要測試的數據庫查詢等

相關問題