【发布时间】:2020-05-29 21:11:44
【问题描述】:
我正在尝试为 SpringBoot 应用程序中的简单控制器编写测试。但是,由于我的 TopicRepository 和 TopicController 的 bean 创建,我收到错误。我参考了一个教程,对 Spring Boot 开发并不陌生,所以不确定它是如何工作的。我怎样才能使测试工作?
控制器测试
@RunWith(SpringRunner.class)
@WebMvcTest(TopicController.class)
public class TopicControllerTest {
@Autowired
private MockMvc mvc;
@MockBean
private TopicService topicService;
@Test
public void whenGetTopics_returnJSONArray()
throws Exception {
Topic topic = new Topic("b","b name", "b descp");
List<Topic> allTopics = new ArrayList<>();
allTopics.add(topic);
Mockito.when(topicService.getAllTopics()).thenReturn(allTopics);
mvc.perform(get("/topics")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].id", is(topic.getId())));
}
}
控制器
@RestController
public class TopicController {
@Autowired
private TopicService topicService; //inject the topicService as a dependency
@Autowired
private TopicRepository topicRepository;
@RequestMapping("/topics")
public List<Topic> getAllTopics() {
return topicService.getAllTopics();
}
@RequestMapping("/topics/{name}")
public Topic getTopic(@PathVariable String name) {
return topicService.getTopic(name);
}
@RequestMapping(method=RequestMethod.POST, value= "/topics")
public void addTopic(@RequestBody Topic topic) {
topicService.addTopic(topic);
}
@RequestMapping(method=RequestMethod.PUT, value = "/topics/{Id}")
public void updateTopic(@RequestBody Topic topic, @PathVariable String Id){
topicService.updateTopic(topic, Id);
}
}
主题库
public interface TopicRepository extends CrudRepository<Topic, String>{
}
我得到的错误是
UnsatisfiedDependencyException:创建名称为“topicController”的 bean 时出错:通过字段“topicRepository”表示不满足的依赖关系;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:没有“io.nkamanoo.springbootstarter.repository.TopicRepository”类型的合格 bean 可用:预计至少有 1 个有资格作为自动装配候选者的 bean。依赖注解:{@org.springframework.beans.factory.annotation.Autowired(required=true)}
【问题讨论】:
-
您没有在测试中定义该回购。只需在您的测试类中使用 @Mock 注释声明它即可。
标签: java spring-boot jpa junit