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的行爲? –