控制器org.springframework.context.NoSuchMessageException中的Springboot Mockito Test和Autowired messageSource [英] Springboot Mockito Test and Autowired messageSource in controller org.springframework.context.NoSuchMessageException

查看:133
本文介绍了控制器org.springframework.context.NoSuchMessageException中的Springboot Mockito Test和Autowired messageSource的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有REST控制器的Springboot应用程序,并为此编写了Mockito单元测试用例.问题是我在运行测试用例时通过在RestController中读取messageSource来获取NoSuchMessageException.但是在实际使用Postman或其他Rest客户端调用它时不会发生.(我使用龙目岛来避免样板代码.)

I have a Springboot app with REST controller and Mockito unit test cases written for it. The problem is I am getting NoSuchMessageException by reading messageSource in the RestController when running the test cases. But not happening when calling it in actually using Postman or other Rest clients. (I use Lombok to avoid boilerplate codes).

其余控制器代码

@RestController
@RequestMapping(value = VERSION + "/product")
@Slf4j
@RequiredArgsConstructor
public class ProductController implements CommonController {

    private final ProductService productService;

    private final MessageSource messageSource;

    
    @PostMapping(path = "")
    public ResponseEntity<CommonResponseDTO> saveProduct(@Valid @RequestBody ProductSaveRequest request) {
        return addNewProduct(request);
    }
    
    private String getMessage(String key) {
        return messageSource.getMessage(key, new Object[0], Locale.getDefault());
    }

}

messageSource配置

The messageSource Config

@Configuration
public class AppConfig {

    @Bean
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasenames("classpath:messages/exception-message", "classpath:messages/success-message");
        messageSource.setCacheSeconds(60); //reload messages every 60 seconds
        return messageSource;
    }
}

测试班

@Slf4j
@ExtendWith(SpringExtension.class)
@WebMvcTest(value = ProductController.class)
class ProductControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private ProductService productService;

    private static final String PRODUCT_PATH = "/v1/product";
    
@Test
    void saveProduct() throws Exception {

        // productService.add to respond back with mockProduct
        Mockito.doNothing().when(productService).add(Mockito.any(Product.class));

        // Send course as body to /students/Student1/courses
        RequestBuilder requestBuilder = MockMvcRequestBuilders
                .post(PRODUCT_PATH)
                .accept(MediaType.APPLICATION_JSON)
                .content("{\n" +
                        "  \"name\": \"Apple\"\n" +
                        "}")
                .contentType(MediaType.APPLICATION_JSON);

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

        MockHttpServletResponse response = result.getResponse();

        assertEquals(HttpStatus.CREATED.value(), response.getStatus());
    }
}

例外

org.springframework.context.NoSuchMessageException: No message found under code 'success.confirmation.common.added.code' for locale 'en_US'.

但是上面的消息存在并成功出现在实际的REST客户端中.

But above message exists and successfully appears in actual REST clients.

项目结构

谢谢.

推荐答案

@WebMvcTest 批注

The @WebMvcTest annotation only loads relevant beans (e.g. Filter, @ControllerAdvice, WebMvcConfigurer) for testing your controller. By default, this TestContext doesn't include any custom @Configuration beans.

您已明确导入配置:

@Slf4j
// @ExtendWith(SpringExtension.class) not needed as part of @WebMvcTest with recent Spring Boot versions
@Import(AppConfig.class)
@WebMvcTest(value = ProductController.class)
class ProductControllerTest {
   
  // your test

}

如果您依赖于 MessageSource 的自动配置,则可以通过 @ImportAutoConfiguration(MessageSourceAutoConfiguration.class)启用它以进行测试.

In case you're relying on the auto-configuration of the MessageSource you can enable it for your test with @ImportAutoConfiguration(MessageSourceAutoConfiguration.class).

这篇关于控制器org.springframework.context.NoSuchMessageException中的Springboot Mockito Test和Autowired messageSource的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆