介绍
特点
- 建立在Cucumber-JVM基础上
- 可以像标准的Java工程一样运行测试并且产生报告
- 测试代码的开发不需要掌握任何的Java知识
- 即使对非编程人员,测试代码也很容易编写
环境需求
- JDK1.8及以上
- Maven
- IDEA
使用
创建工程
- 打开IDEA,File|New|Project

- 选择Maven工程,点击Next

- 输入Maven基本信息,点击Next

- 输入工程名称和存放路径,点击Finish

添加依赖
要在Maven项目中使用Karate,需要将karate-apache依赖项添加到pom.xml,如果实现JUnit测试还需要添加karate-junit4依赖
com.intuit.karate
karate-apache
0.8.0
test
com.intuit.karate
karate-junit4
0.8.0
test
设置测试资源文件目录,建议测试用例文件和java文件放在同一个目录下,遇到庞大的工程的时候方便管理,不必在文件夹src/test/java和src/test/resources文件夹之间切换,可以在pom.xml的标签中添加一下设置
src/test/java
/*.java
服务端模拟
com.github.tomakehurst
wiremock-standalone
2.18.0
test
编写一个启动服务的类
package server; import com.github.tomakehurst.wiremock.WireMockServer; import static com.github.tomakehurst.wiremock.client.WireMock.*; public class StartServer {
private static WireMockServer wireMockServer = new WireMockServer(8080); public static void startServer(){
wireMockServer.start(); stubFor( get(urlEqualTo("/user/get")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{ \"id\": \"1234\", name: \"John Smith\" }"))); stubFor( post(urlEqualTo("/user/create")) .withHeader("content-type", equalTo("application/json")) .withRequestBody(containing("id")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{ \"id\": \"1234\", name: \"John Smith\" }"))); } public static void main(String... args){
startServer(); } }
用例文件编写
Feature: Learn How to use Karate for testing. Scenario: Testing valid GET endpoint Given url 'http://localhost:8080/user/get' When method GET Then status 200 Scenario: Testing the exact response of a GET endpoint Given url 'http://localhost:8080/user/get' When method GET Then status 200 And match $ == {id:"1234", name:"John Smith"} Scenario: Testing that GET response contains specific field Given url 'http://localhost:8080/user/get' When method GET Then status 200 And match $ contains {id:"1234"}
Runner类编写
package demo; import com.intuit.karate.junit4.Karate; import cucumber.api.CucumberOptions; import org.junit.runner.RunWith; @RunWith(Karate.class) @CucumberOptions(features = "classpath:demo/demo.feature") public class DemoRunner {
}
运行用例
- 先启动服务
右击StartServer类选择Run StartServer.main()启动服务
- 运行用例
右击DemoRunner类选择Run DemoRunner运行测试
查看报告
持续集成
com.intuit.karate karate-testng 0.8.0 修改DemoRunner,注意配置CucumberOptions,要产生json格式的报告,cucumber-reports插件会去解析该文件并生成报告
package demo; import com.intuit.karate.junit4.Karate; import com.intuit.karate.testng.KarateRunner; import cucumber.api.CucumberOptions; import org.junit.runner.RunWith; @CucumberOptions(features = "classpath:demo/demo.feature",format={
"pretty","html:reports","json:report.json"}) public class DemoRunner extends KarateRunner {
}

jenkins报告展示

代码参考地址: https://github.com/ouguangqian/demo4Karate
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/224321.html原文链接:https://javaforall.net
