-1

I make JUnit tests for SpringBoot rest controllers. When i start tests i get the next error:

enter image description here

I suppose it appears because of BookRepository class is autowired into Controller class. Because of legacy i cannot change this Controller class. What i need to do?

In addition this is my test method:

Here are emulation of real code:

@RunWith(SpringRunner.class)
@WebMvcTest(value = AuthorController.class, secure = false)
public class AuthorControllerTest {
    private static final Long AUTHOR_ID = 1L;

    @Autowired
    MockMvc mockMvc;

    @MockBean
    private AuthorService authorService;

    AuthorShortDTO authorShortDTO;
    AuthorShortDTO authorShortDTO1;
    List<AuthorShortDTO> authorShortDTOList;

    @Before
    public void setUp() throws Exception{
        authorShortDTO = new AuthorShortDTO();
        authorShortDTO.setId(1L);
        authorShortDTO.setFirstName("Alex");
        authorShortDTO.setMiddleName("");
        authorShortDTO.setLastName("Menn");

        authorShortDTO1 = new AuthorShortDTO();
        authorShortDTO1.setId(2L);
        authorShortDTO1.setFirstName("Den");
        authorShortDTO1.setMiddleName("");
        authorShortDTO1.setLastName("Rob");

        authorShortDTOList = new ArrayList<>();

        authorShortDTOList.add(authorShortDTO);
        authorShortDTOList.add(authorShortDTO1);
    }

    @Test
    public void getAuthorsTest() throws Exception {
        Mockito.when(authorService.getAuthors()).thenReturn(authorShortDTOList);

        RequestBuilder requestBuilder = MockMvcRequestBuilders.get(
            "/author").accept(MediaType.APPLICATION_JSON);

        MvcResult result = mockMvc.perform(requestBuilder).andReturn();

        String expected = "[{id:1, firstName:Alex, middleName:, lastName:Menn}, " +
            "{id:2, firstName:Den, middleName:, lastName:Rob}]";

        JSONAssert.assertEquals(expected, result.getResponse()
            .getContentAsString(), false);
    }

Rest controller class:

@RestController
public class AuthorController extends BasicExceptionHandler {

    private final AuthorService service;

    private final BookRepository bookRepository;//if i exclude this repo it will ok when testing

    @Autowired
    public AuthorController(AuthorService service, BookRepository bookRepository) {
        this.service = service;
        this.bookRepository = bookRepository;
    }

    @RequestMapping(value = "/author", method = RequestMethod.GET)
    public List<AuthorShortDTO> getAuthors() {
        return service.getAuthors();
    }

    @RequestMapping(value = "/author/{id}", method = RequestMethod.GET)
    public AuthorShortDTO getAuthor (
            @PathVariable("id") long id) throws EntityNotFoundException {
        bookRepository.getOne(1L);//emulate real code

        return service.getAuthor(id);
    }
 ...
}

Error message from Intellij output:

2018-10-04 20:49:24.258  WARN 6982 --- [           main] o.s.w.c.s.GenericWebApplicationContext   : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'authorController' defined in file [/home/max/java_projects/bookshelter/serverparent/rest/target/classes/ru/arvsoft/server/rest/controller/AuthorController.class]: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'ru.arvsoft.server.core.repository.BookRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
2018-10-04 20:49:24.265  INFO 6982 --- [           main] utoConfigurationReportLoggingInitializer : 

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2018-10-04 20:49:24.316 ERROR 6982 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 1 of constructor in ru.arvsoft.server.rest.controller.AuthorController required a bean of type 'ru.arvsoft.server.core.repository.BookRepository' that could not be found.


Action:

Consider defining a bean of type 'ru.arvsoft.server.core.repository.BookRepository' in your configuration.
jlemon
  • 95
  • 1
  • 9

1 Answers1

1

required a bean of type 'ru.arvsoft.server.core.repository.BookRepository' that could not be fou

Thats kid of self explainatory isnt it? Your tested beans requires BookRepository but you are not creating one in the context (nor mocking it). Add

@MockBean
private BookRepository bookRepository;
Antoniossss
  • 31,590
  • 6
  • 57
  • 99