Lao*_*dao 5 junit spring unit-testing 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);
}
...
}
Run Code Online (Sandbox Code Playgroud)
测试类是
@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());
}
...
}
Run Code Online (Sandbox Code Playgroud)
但是,我收到错误消息,抱怨说我创建名为“eventController”的 bean 时出错:
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)}.
Run Code Online (Sandbox Code Playgroud)
由于出现上述错误,我尝试对我的 EventService 使用 Autowired 注释。它仍然不起作用。有任何想法吗?谢谢。
我找到了解决方案。我需要做的就是将@WebMvcTest(EventController.class)我的测试类替换为@SpringBootTest(classes = Application.class). 多谢你们。
小智 0
您是否在EventService中声明了@Service注释?
@Service
public class EventService {
...something code..
}
Run Code Online (Sandbox Code Playgroud)
我猜Spring找不到名为EventService的bean
| 归档时间: |
|
| 查看次数: |
11649 次 |
| 最近记录: |