1. 程式人生 > >解決junit測試問題:initializationError+java.lang.NullPointerException

解決junit測試問題:initializationError+java.lang.NullPointerException

1.確定匯入依賴:

 <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
<dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>

2.確定匯入匯入了正確的依賴包:

千萬注意,匯入的包的是 :

org.junit.Test;

千萬不要導成 org.junit.jupiter.api.Test;,否則會報:java.lang.NullPointerException和initializationError

3.測試類要寫成public型別,測試方法也要要寫成public 。。。並且測試方法要用@Test註解,,測試方法為public void型別的方法,否則也會報initializationError

4.確保你的spring配置檔案的指定路徑是對的,spring的配置檔案沒有問題,,所有的spring配置檔案都被載入了進來,測試的介面類被載入進了spring的容器中。

下面附上我的程式碼以供參考(宣告式和註解式的)

註解式:

service介面的測試程式碼:

@RunWith(SpringJUnit4ClassRunner.class)//使用junit4進行測試
@ContextConfiguration(locations = {"classpath:spring/applicationContext.xml"})
public class ItemsServiceTest {
    @Autowired
    private ItemsService itemsService;
    @Test
    public void lmj() throws Exception {
        //ItemsService itemsService=new ItemsServiceImpl();
        // ItemsService  itemsService= (ItemsService) applicationContext.getBean("itemsService");
        Items items = itemsService.lmj();
        System.out.println(items);
        System.out.println(items);
    }
}