prosource

"@WebMvcTest"에 빈 하나 추가

probook 2023. 8. 1. 20:38
반응형

"@WebMvcTest"에 빈 하나 추가

@WebMvcTest를 사용한 컨트롤러와 테스트가 있으며 정상적으로 실행되고 있습니다.이제 나는 약간의 검증 논리를 추가해야 했고 이것을 위해 나는.@Autowired추가 콩(a)@Component지도 구조 지도자).

예상대로 지금 시험은 실패하고 있습니다.@WebMvcTest(구성 요소가 발견되지 않음)

생성된 컨텍스트에 빈 하나를 추가할 수 있는 방법이 있습니까?

사용하고 있기 때문에@MockBeans모의 서비스 계층: 모든 모의 통화를 실제 객체에 위임하는 방법이 있습니까?이것으로 지도 제작자를 조롱하고 진짜 지도 제작자에게 위임할 수 있습니까?!

매우 간단한 해결책은 테스트 클래스에 주석을 다는 것입니다.@Import문서에 명시된 대로 테스트에 사용할 추가 콩의 종류를 지정합니다.

일반적으로 @WebMvcTest는 @MockBean 또는 @Import와 함께 사용하여 @Controller Bean에 필요한 공동작업자를 만듭니다.

예.

@WebMvcTest(MyController.class)
@Import(SomeOtherBean.class)
public class SourcingOrganisationControllerTests {

    // The controller bean is made available via @WebMvcTest  
    @Autowired
    private MyController myController;

    // Additional beans (only one in this case) are made available via @Import
    @Autowired
    private SomeOtherBean someOtherBean;
}

컨텍스트에서 빈을 추가하는 간단한 방법은 테스트 클래스 내에 중첩된 구성 클래스를 사용하는 것입니다.

@TestConfiguration
static class AdditionalConfig {
    @Bean
    public SomeBean getSomeBean() {
        return new SomeBean());
    }
}

예:

시나리오 - 일부 컨트롤러가 ProductController라고 하며 클래스에 해당하는 슬라이스 테스트가 있는 경우 ProductControllerTest라고 합니다.

@RestController
public class ProductController {

    @Autowired
    private IProductService productService;

    @Autowired
    private IProductValidator productValidator;


    @GetMapping("product")
    public Product getProduct(@RequestParam Long id) {

        Product product = productService.getProduct(id); // you are using mockBean of productService

        productValidator.validateProduct(product); // you need real bean of productValidator
        return product;
    }
}

추가 Bean 구성이 있는 해당 슬라이드 테스트 클래스

@RunWith(SpringRunner.class)
@WebMvcTest
public class ProductControllerSliceTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private IProductService productService;

    @Autowired
    private ApplicationContext applicationContext;

    @TestConfiguration
    static class AdditionalConfig {
        @Bean
        public IProductValidator productValidator() {
            return new ProductValidator();
        }
    }


    @Test
    public void testProductGetById() throws Exception {
        Product testProductWithID1L = new Product(1L, "testProduct");
        when(productService.getProduct(anyLong())).thenReturn(testProductWithID1L);

        mockMvc.perform(get("/product")
                .param("id", "1")).andDo(print())
                .andExpect(status().isOk())
                .andExpect(jsonPath("name")
                        .value("testProduct"))
                .andExpect(MockMvcResultMatchers.jsonPath("id")
                        .value("1"));
    }
}

시나리오에 대한 추가 의견: 컨트롤러 클래스의 단위 테스트를 수행하려는 경우 테스트 중인 클래스의 모든 추가 종속성을 조롱해야 합니다.단위 테스트의 목적은 테스트 대상 객체/클래스의 동작만 테스트하는 것이 이상적입니다.모든 종속 클래스 동작 또는 외부 호출은 조롱되어야 합니다.
하나의 테스트에서 여러 클래스를 함께 테스트하기 시작하면 구성 요소 테스트 또는 통합 테스트로 이동하게 됩니다.

언급URL : https://stackoverflow.com/questions/56021699/add-one-additional-bean-to-webmvctest

반응형