Как написать тестовые примеры загрузки Spring в нескольких файлах для нескольких контроллеров соответственно

Я использую JUnit и Mockito для написания тестовых примеров для Spring Boot Application. У меня есть несколько контроллеров (например, ContractController и CountryCOntroller). Когда я пишу тестовые примеры для них обоих в одном файле, тест будет пройден, но если я напишу тестовые примеры ContractController в один файл, а тестовые примеры другого контроллера во втором файле, тестовые примеры завершатся ошибкой. Подскажите, пожалуйста, как писать в разных файлах?

Контроллер контракта TEst

package com.example.demo;

import static org.junit.Assert.*;

import java.util.Collections;
import java.util.Optional;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

import com.example.demo.controllers.ContractController;
import com.example.demo.controllers.CountryController;
import com.example.demo.entities.Contract;
import com.example.demo.entities.Country;
import com.example.demo.repositories.ContractRepository;
import com.example.demo.repositories.CountryRepository;

@RunWith(SpringRunner.class)
public class ContractControllerTest {

    @Autowired
    private MockMvc mockMvc;
    @MockBean
    private ContractRepository contractRepository;

    @SuppressWarnings("unchecked")
    @Test
    public void testGetContract() throws Exception {
        System.out.println("contract testing");
        Contract contract = new Contract();
        contract.setContractTypeId(1);
        contract.setContractType("Calibration");
        Mockito.when(this.contractRepository.findAll()).thenReturn((Collections.singletonList(contract)));

        RequestBuilder requestBuilder = MockMvcRequestBuilders.get("/api/contractType").accept(MediaType.APPLICATION_JSON_UTF8);
        MvcResult result = mockMvc.perform(requestBuilder).andReturn();
        System.out.println("result is"+result.getResponse().getContentAsString());
         String expected = "[{id:1,contractType:Calibration}]";
        JSONAssert.assertEquals(expected, result.getResponse().getContentAsString(), false);    
    }
}

COuntry COntroller Test

package com.example.demo;
import static org.junit.Assert.*;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

import org.json.JSONObject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

import com.example.demo.controllers.CountryController;
import com.example.demo.entities.Contract;
import com.example.demo.entities.Country;
import com.example.demo.repositories.ContractRepository;
import com.example.demo.repositories.CountryRepository;


@RunWith(SpringRunner.class)
@WebMvcTest(value = CountryController.class)
public class CountryControllerTest {

    @Autowired
    private MockMvc mockMvc;
    @MockBean
    private CountryRepository countryRepository;

    @MockBean
    private ContractRepository contractRepository;


    @SuppressWarnings("unchecked")
    @Test
    public void testGetCountries() throws Exception {
        System.out.println("mockito testing");
        Country country = new Country();
        country.setId(1);
        country.setCountryName("Afghanistan");
        country.setShortName("AF");
        Mockito.when(this.countryRepository.findAll()).thenReturn((Collections.singletonList(country)));

        RequestBuilder requestBuilder = MockMvcRequestBuilders.get("/api/countries").accept(MediaType.APPLICATION_JSON_UTF8);
        MvcResult result = mockMvc.perform(requestBuilder).andReturn();
        System.out.println("result is"+result.getResponse().getContentAsString());
         String expected = "[{id:1,shortName:AF,countryName:Afghanistan}]";
        JSONAssert.assertEquals(expected, result.getResponse().getContentAsString(), false);    
    }

Можете ли вы предоставить дополнительную информацию о том, как они выходят из строя, когда они являются отдельными файлами?

user3127632 05.10.2018 00:27

Какой тест не проходит? Вашему ContractControllerTest нужен @WebMvcTest или что-то еще.

Min Hyoung Hong 05.10.2018 02:46

Сообщение об ошибке, когда они являются отдельными файлами org.springframework.beans.factory.UnsatisfiedDependencyExcep‌tion: Ошибка при создании bean-компонента с именем com.example.demo.ContractControllerTest: неудовлетворенная зависимость выражена через поле mockMvc; вложенное исключение - org.springframework.beans.factory.NoSuchBeanDefinitionExcept‌ ion: Нет подходящего bean-компонента типа org.springframework.test.web.servlet.MockMvc: ожидается как минимум 1 bean-компонент, который квалифицируется как кандидат autowire. Аннотации зависимостей: {@ org.springframework.beans.factory.annotation.Autowired (req‌ uired = true)}

Veda 05.10.2018 15:22

@WebMvcTest можно использовать только в одном контроллере #Min Hyoung Hong

Veda 05.10.2018 15:24
0
4
893
0

Другие вопросы по теме