0

我正在为一个控制器编写单元测试,这是我的代码

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();
    }
}

当它尝试加载 aService 和 bService 时,我在 MyControllerTest 中为 myService 创建 bean 时遇到错误。

有人可以帮忙吗?还有其他人遇到过类似的问题吗?

堆栈跟踪:

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)
4

1 回答 1

-1

您需要提供所有模拟实现,即。你的测试类无法弄清楚这些AService是什么aService;b服务 b服务;是。

@mock 将查看所有要呈现的字段(模拟)

因此,您可以为他们提供模拟提供模拟实现

..

private MockMvc standAloneMockMvc;

    @InjectMocks
    MyController myController;

    @Mock
    private MyService myService;

    @Mock
    AService aService;

    @Mock
    BService bService;

……

于 2016-10-04T09:33:24.203 回答