spring-boot - Controller org.springframework.context.NoSuchMessageException 中的 Springboot Mockito 测试和 Autowiring 消息源

标签 spring-boot unit-testing mockito junit5 spring-test

我有一个带有 REST Controller 和为其编写的 Mockito 单元测试用例的 Springboot 应用程序。问题是我在运行测试用例时通过读取 RestController 中的 messageSource 得到了 NoSuchMessageException。 但是在实际使用 Postman 或其他 Rest 客户端调用它时不会发生。 (我使用 Lombok 来避免样板代码)。

其余 Controller 代码

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

}

消息源配置

@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 客户端中。

项目结构

enter image description here

提前致谢。

最佳答案

只有@WebMvcTest注解loads relevant beans (例如 Filter@ControllerAdviceWebMvcConfigurer)用于测试您的 Controller 。默认情况下,此 TestContext 不包含任何自定义 @Configuration bean。

您已明确导入您的配置:

@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) 为您的测试启用它。

关于spring-boot - Controller org.springframework.context.NoSuchMessageException 中的 Springboot Mockito 测试和 Autowiring 消息源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66166601/

相关文章:

java - Mockito 依赖于先前调用的链接方法调用无法识别

java - (SpringBoot 使用 Amazon S3 存储桶调用 Textract): error The method builder() is undefined for the type Document

java - Spring 上有重复的 AWS S3 Bean,但找不到重复的内容

java - 覆盖 Java 单元测试中的异常语句

java - 乔比 : How to properly unit test a route that returns different content depending on MediaType?

java - Android 单元测试内容解析器类

java - 设置 Zookeeper 仅为每个应用程序实例传递一次配置 [Spring]

postgresql - 如何使用 springboot 和 hibernate 传递 jdbc 参数?

unit-testing - 您至少编写过 'worth it' 单元测试吗?

unit-testing - "Unit Testing"属于白盒测试还是黑盒测试?