簡體   English   中英

無法為 Spring Boot 控制器創建 JUnit 測試

[英]Unable to create JUnit Test for Spring Boot Controller

我正在嘗試為 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)}

您需要使用@SpringBootTest注釋您的測試類,以便它創建所有定義的 bean 並啟動您的應用程序以運行測試用例。

在您的代碼中:

@RunWith(SpringRunner.class)
@WebMvcTest(TopicController.class)
@SpringBootTest
public class TopicControllerTest {
}

我正在嘗試為SpringBoot應用程序中的簡單Controller編寫測試。 但是,由於為我的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)}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM