在我的Java弹簧MVC应用, 我面对NullPointException在我的JUnit测试,所有的类都位于某个包,我有它们如下面main
方法NullpointException在JUnit测试
@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[] reteriveAllData();
}
的实现如下:
@Service
public class DataServiceImpl implements DataService {
@Override
public int[] reteriveAllData() {
return new int[] { 1, 2, 3, 4 };
}
}
,然后我使用的服务,如下面另一个类:
public class SomeBussiness {
@Autowired
DataServiceImpl dataService;
public int findTheGreat() {
int[] res = dataService.reteriveAllData();
return res[0];
}
}
的我写了一个测试,以检查findTheGreattest()
在SomeBussiness
类:
public class SomeBussinessTest {
@Test
public void findTheGreatTest() {
SomeBussiness sbi = new SomeBussiness();
int res = sbi.findTheGreatest();
assertEquals(1, res);
}
}
但它与NullPointException
在抱怨行
int[] res = dataService.reteriveAllData();
但是,我有你sed @Service
和@Autowiered
注入dataService
我该如何解决它?
更新:
我已经加入@Service
的SomeBussiness
类:
@Service
public class SomeBussiness {
@Autowired
DataServiceImpl dataService;
public int findTheGreat() {
int[] res = dataService.reteriveAllData();
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)}
由于新的关键字。当你使用new创建一个实例时,Spring的依赖关系不会发生,你必须确保传递依赖关系。 – Barath
我不明白你的意思。你能写一个答案吗? –