简体   繁体   中英

Unable to create JUnit Test for Spring Boot Controller

I am trying to write a test for a simple Controller in SpringBoot application. However, I am receiving errors due to bean creations for my TopicRepository and TopicController. I had referenced a tutorial and am little new to Spring boot development so not sure exactly how it works. How can I make the test work?

ControllerTest

@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())));

        }       
}

Controller

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

}

TopicRepository

public interface TopicRepository extends CrudRepository<Topic, String>{

}

The errors I am getting are

UnsatisfiedDependencyException: Error creating bean with name 'topicController': Unsatisfied dependency expressed through field 'topicRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'io.nkamanoo.springbootstarter.repository.TopicRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

You need to annotate your test class with @SpringBootTest so it will create all defined beans and start your app to run test cases.

In your code:

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

I am trying to write a test for a simple Controller in SpringBoot application. However, I am receiving errors due to bean creations for my TopicRepository and TopicController. I had referenced a tutorial and am little new to Spring boot development so not sure exactly how it works. How can I make the test work?

ControllerTest

@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())));

        }       
}

Controller

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

}

TopicRepository

public interface TopicRepository extends CrudRepository<Topic, String>{

}

The errors I am getting are

UnsatisfiedDependencyException: Error creating bean with name 'topicController': Unsatisfied dependency expressed through field 'topicRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'io.nkamanoo.springbootstarter.repository.TopicRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM