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

使用RestTemplate进行RESTful Services测试

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

使用RestTemplate进行RESTful Services测试

文档中有一章很好的章节,建议您通读它以完全理解您可以做什么。

我喜欢使用

@IntegrationTest
自定义配置,因为它可以启动整个服务器并允许您测试整个系统。如果要用模拟替换系统的某些部分,可以通过排除某些配置或bean并用自己的替换来实现。

这是一个小例子。我省略了该

MessageService
接口,因为它从功能上显而易见
IndexController
,并且是默认实现
DefaultMessageService
--因为它不相关。

它的作用是将整个应用程序减至最小,

DefaultMessageService
但将其自身
MessageService
保留。然后,它
RestTemplate
用于在测试用例中向正在运行的应用程序发出实际的HTTP请求。

应用类别:

IntegrationTestDemo.java:

@SpringBootApplicationpublic class IntegrationTestDemo {    public static void main(String[] args) {        SpringApplication.run(IntegrationTestDemo.class, args);    }}

IndexController.java:

@RestControllerpublic class IndexController {    @Autowired    MessageService messageService;    @RequestMapping("/")    String getMessage() {        return messageService.getMessage();    }}

测试类别:

IntegrationTestDemoTest.java:

@RunWith(SpringJUnit4ClassRunner.class)@SpringApplicationConfiguration(classes = TestConfig.class)@WebIntegrationTest // This will start the server on a random portpublic class IntegrationTestDemoTest {    // This will hold the port number the server was started on    @Value("${local.server.port}")    int port;    final RestTemplate template = new RestTemplate();    @Test    public void testGetMessage() {        String message = template.getForObject("http://localhost:" + port + "/", String.class);        Assert.assertEquals("This is a test message", message);    }}

TestConfig.java:

@SpringBootApplication@ComponentScan(    excludeFilters = {        // Exclude the default message service        @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = DefaultMessageService.class),        // Exclude the default boot application or it's        // @ComponentScan will pull in the default message service        @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = IntegrationTestDemo.class)    })public class TestConfig {    @Bean    // Define our own test message service    MessageService mockMessageService() {        return new MessageService() { @Override public String getMessage() {     return "This is a test message"; }        };    }}


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

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

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