[英]NullpointException in junit test
在我的java spring mvc應用程序中,在我的junit測試中我遇到一個NullPointerException,所有類都位於某個包中,我已經在main
方法中按以下方式解決了這些問題
@SpringBootApplication
@ComponentScan({ "com.example.model" })
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
然后在com.example.model
我具有以下類和接口:
public interface DataService {
int[] retrieveAllData();
}
實現如下:
@Service
public class DataServiceImpl implements DataService {
@Override
public int[] retrieveAllData() {
return new int[] { 1, 2, 3, 4 };
}
}
然后我在另一個類中使用了以下服務:
public class SomeBussiness {
@Autowired
DataServiceImpl dataService;
public int findTheGreat() {
int[] res = dataService.retrieveAllData();
return res[0];
}
}
我編寫了一個測試來檢查SomeBussiness
類中的findTheGreattest()
:
public class SomeBussinessTest {
@Test
public void findTheGreatTest() {
SomeBussiness sbi = new SomeBussiness();
int res = sbi.findTheGreatest();
assertEquals(1, res);
}
}
但它抱怨與NullPointException
一致
int[] res = dataService.retrieveAllData();
但是,我已經使用@Service
和@Autowiered
注入dataService
我該如何解決?
更新:
我添加了@Service
SomeBussiness
類:
@Service
public class SomeBussiness {
@Autowired
DataServiceImpl dataService;
public int findTheGreat() {
int[] res = dataService.retrieveAllData();
return res[0];
}
}
然后添加更改測試,如下所示:
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = DemoApplication.class)
public class SomeBussinessTest {
@Autowired
SomeBussiness sbi;
@Test
public void findTheGreatestTest() {
assertEquals(1, sbi.findTheGreatest());
}
}
現在它抱怨:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.example.demo.SomeBussinessTest': Unsatisfied dependency expressed through field 'sbi'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.model.SomeBussiness' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
您課程中的自動裝配永遠不會觸發。 首先,您需要一個用於初始化所有測試類的JUnit運行器。 另外,您必須通過此運行器創建要測試的類,而不是通過調用“ new”來創建它:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {DemoApplication.class})
public class SomeBussinessTest {
@Autowired
SomeBussiness sbi;
@Test
public void findTheGreatTest() {
int res = sbi.findTheGreatest();
assertEquals(1, res);
}
}
因為有新關鍵字。 當您使用新的實例創建實例時,spring的依賴項注入將不會發生,您必須確保通過構造函數或setter傳遞依賴項。
@Test
public void findTheGreatTest() {
SomeBussiness sbi = new SomeBussiness();
sbi.setDataService(dbService);
int res = sbi.findTheGreatest();
assertEquals(1, res);
}
使用SpringRunner
:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoApplication.class)
public class SomeBussinessTest {
@Autowired
SomeBussiness sbi;
@Test
public void findTheGreatestTest() {
assertEquals(1, sbi.findTheGreatest());
}
}
這篇文章清楚地說明了new關鍵字的作用:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.