问题描述
我有一个带有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
批注加载相关的bean (例如 Filter
, @ControllerAdvice
, WebMvcConfigurer 代码>)来测试您的控制器.默认情况下,此TestContext不包含任何自定义
@Configuration
bean.
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!