单元测试 - 没有ERROR类型的限定bean

时间:2018-03-13 05:14:37

标签: spring unit-testing junit mocking mockito

我正在尝试对我的其他api控制器进行单元测试。控制器代码如下

    @RestController
    @RequestMapping("/events")
    public class EventController {

        @Autowired
        private EventService eventService;

        @GetMapping
        public Iterable<Event> getEvents(EventSearchFilter filter, @PageableDefault(page = 1, size = 5, sort = "location.city, asc") Pageable pageable) {
            return eventService.findEventsOnCondition(filter, pageable);
        }
        ...
    }

测试类是

@RunWith(SpringRunner.class)
@WebMvcTest(EventController.class)
public class EventEndpointTest {

    private MockMvc mockMvc;

    @InjectMocks
    private EventController eventController;

    @Mock
    private EventService eventService;

    @InjectMocks
    private PageableHandlerMethodArgumentResolver pageableArgumentResolver;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        this.mockMvc = MockMvcBuilders.standaloneSetup(eventController).setCustomArgumentResolvers(pageableArgumentResolver).build();
    }

    @Test
    public void getEvents() throws Exception{
        Event event = new Event();
        event.setName("TestName");
        EventSearchFilter filter = new EventSearchFilter();
        filter.setName("TestName");
        List<Event> eventList = singletonList(event);
        given(eventController.getEvents(any(EventSearchFilter.class), any(PageRequest.class))).willReturn(eventList);
        mockMvc.perform(get("/events")
                .contentType(APPLICATION_JSON))
                .andExpect(status().isOk());

    }
    ...
}

然而,我得到错误抱怨说我创建了名为&#39; eventController&#39;的错误:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'EventService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}. 

当我遇到上述错误时,我尝试使用Autowired annotation for EventService。它仍然无法运作。有任何想法吗?感谢。

3 个答案:

答案 0 :(得分:1)

我找到了解决方案。我需要做的就是将我的Test类中的@WebMvcTest(EventController.class)替换为@SpringBootTest(classes = Application.class)。谢谢你们。

答案 1 :(得分:0)

您是否在EventService上声明@Service注释?

@Service
public class EventService {
 ...something code..
}

我猜Spring无法找到名为EventService的bean

答案 2 :(得分:0)

我有一个类似的问题,堆栈跟踪显示

java.lang.IllegalStateException: Failed to load ApplicationContext
...
...
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'Controller': Unsatisfied dependency expressed through field 'i18NService'; 
...
...
...
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type '...Service' available:
...
...
...

最终的解决方案是需要使用 @MockBean 模拟服务,因为不会扫描常规组件(包括服务和存储库)。