栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何彻底测试使用DomainClassConverter检索参数的Spring控制器?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何彻底测试使用DomainClassConverter检索参数的Spring控制器?

因此,从DomainClassConverter小型文档中,我知道它使用CrudRepository#findById查找实体。我想知道的是如何在测试中清晰地进行模拟。

您将需要模拟2个在之前调用的方法,

CrudRepository#findById
以便返回所需的实体。下面的示例使用
RestAssuredMockMvc
,但是如果同时注入MockMvc,则可以执行相同的操作
WebApplicationContext

@RunWith(SpringRunner.class)@SpringBootTest(classes = SomeApplication.class)public class SomeControllerTest {    @Autowired    private WebApplicationContext context;    @MockBean(name = "mvcConversionService")    private WebConversionService webConversionService;    @Before    public void setup() {        RestAssuredMockMvc.webAppContextSetup(context);        SomeEntity someEntity = new SomeEntity();        when(webConversionService.canConvert(any(TypeDescriptor.class), any(TypeDescriptor.class)))     .thenReturn(true);        when(webConversionService.convert(eq("1"), any(TypeDescriptor.class), any(TypeDescriptor.class)))     .thenReturn(someEntity);    }}

在某个时候,Spring
Boot将执行

WebConversionService::convert
,稍后将调用
DomainClassConverter::convert
,然后执行类似的操作
invoker.invokeFindById
,该操作将使用实体存储库查找实体。

那么为什么要模拟

WebConversionService
而不是
DomainClassConverter
呢?因为
DomainClassConverter
是在应用程序启动期间实例化的,没有注入:

DomainClassConverter<FormattingConversionService> converter =        new DomainClassConverter<>(conversionService);

同时,

WebConversionService
是一个可以让我们模拟它的bean:

@Bean@Overridepublic FormattingConversionService mvcConversionService() {    WebConversionService conversionService = new WebConversionService(this.mvcProperties.getDateFormat());    addFormatters(conversionService);    return conversionService;}

将模拟bean命名为

mvcConversionService
,这一点很重要,否则它将不会替换原始bean。

关于存根,您将需要模拟2个方法。首先,您必须告诉您的模拟可以转换任何内容:

when(webConversionService.canConvert(any(TypeDescriptor.class), any(TypeDescriptor.class)))        .thenReturn(true);

然后是main方法,它将与URL路径中定义的所需实体ID相匹配:

when(webConversionService.convert(eq("1"), any(TypeDescriptor.class), any(TypeDescriptor.class)))        .thenReturn(someEntity);

到目前为止,一切都很好。但是匹配目标类型也不会更好吗?像

eq(TypeDescriptor.valueOf(SomeEntity.class))
什么?可以,但是这会创建TypeDescriptor的新实例,当在域转换期间调用此存根时,它将不匹配。

这是我使用过的最干净的解决方案,但是我知道,如果Spring允许的话,可能会更好。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/470860.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号