0
我写单元测试的一个控制器,这里是我的代码基于的Mockito JUnit测试类进样嵌套的相关
public class MyController
{
@Inject
private MyService myService;
public List<Car> getCars()
{
myService.getCars();
}
}
public class MyServiceImpl implements MyService
{
@Inject
AService aService;
@Inject
BService bService;
public List<Car> getCars()
{
aService.getCars();
}
}
Public class MyControllerTest
{
private MockMvc standAloneMockMvc;
@InjectMocks
MyController myController;
@Mock
private MyService myService;
@Before
public void initTestObjs()
{
MockitoAnnotations.initMocks(this);
this.standAloneMockMvc = MockMvcBuilders.standaloneSetup(myController).build();
}
@Test
public void testGetAllCars() throws Exception
{
String url = "/car/list";
List<Car> listCars = new ArrayList<Car>();
Car car = new Car();
listCars.add(car);
Mockito.when(myService.getCars()).thenReturn(listCars);
MvcResult result = standAloneMockMvc.perform(MockMvcRequestBuilders.get(url))
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn();
String jsonResult = result.getResponse().getContentAsString();
}
}
我在为MyControllerTest为myService创造豆面对错误时,它会尝试加载aService和bService。
任何人都可以帮忙吗?任何人都面临类似的问题?
堆栈跟踪:
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.xyz.AService com.xyz.aService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.xyz.AService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@javax.inject.Inject()}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:571)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
你能提供错误信息吗?对于调试 –
编辑的问题,它更容易实现,增加了堆栈跟踪错误消息。 – Jaynil
您是否尝试过验证在MyControllerTest中有模拟AService和BService的行为? –