Хранилище в ошибке перехвата контроллера остатка "Параметр 1 конструктора не найден

Я делаю тесты JUnit для остальных контроллеров SpringBoot. Когда я запускаю тесты, я получаю следующую ошибку:

Я предполагаю, что это появляется из-за того, что класс BookRepository автоматически подключен к классу Controller. Из-за наследства я не могу изменить этот класс контроллера. Что я должен сделать?

Кроме того, это мой метод испытаний:

Вот эмуляция реального кода:

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

Регулятор отдыха класса:

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

Сообщение об ошибке с выхода Intellij:

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.

1 ответ

Решение

требуется bean-компонент типа 'ru.arvsoft.server.core.repository.BookRepository', который не может быть найден

Это ребенок самообороны не так ли? Ваши проверенные бобы требуют BookRepository но вы не создаете один в контексте (и не насмехаетесь над ним). добавлять

@MockBean
private BookRepository bookRepository;
Другие вопросы по тегам