Spring 单元测试-没有类型错误的合格bean

Spring 单元测试-没有类型错误的合格bean,spring,unit-testing,junit,mocking,mockito,Spring,Unit Testing,Junit,Mocking,Mockito,我正在尝试对我的RESTAPI控制器进行单元测试。控制器代码如下所示 @RestController @RequestMapping("/events") public class EventController { @Autowired private EventService eventService; @GetMapping public Iterable<Event> getEvent

我正在尝试对我的RESTAPI控制器进行单元测试。控制器代码如下所示

    @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);
        }
        ...
    }

当我遇到上述错误时,我尝试对我的EventService使用Autowired注释。它仍然不起作用。有什么想法吗?谢谢。

您是否在EventService上声明@Service annotation

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

我猜Spring找不到名为EventService的bean,我找到了一个解决方案。我需要做的就是将测试类中的
@WebMvcTest(EventController.class)
替换为
@SpringBootTest(classes=Application.class)
。谢谢各位。

是的。是的。我的控制器可以与@autowired private enventservice eventService配合使用。此问题仅在我的单元测试中出现。
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)}. 
@Service
public class EventService {
 ...something code..
}