首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >空手道:如何测试多部分表单数据端点?

空手道:如何测试多部分表单数据端点?
EN

Stack Overflow用户
提问于 2019-04-12 04:27:39
回答 1查看 4.1K关注 0票数 3

我在控制器中有一个文件上传端点(/document),定义如下:

代码语言:javascript
复制
@RestController
public class FileUploadController {

    @Autowired
    private PersonCSVReaderService personCSVReaderService;

    @PostMapping(value = "/document", consumes= {MediaType.MULTIPART_FORM_DATA_VALUE})
    public void handleFileUpload3(@RequestPart("file") MultipartFile file, @RequestPart("metadata") DocumentMetadata metadata) {
        System.out.println(String.format("uploading file %s of %s bytes", file.getOriginalFilename(), file.getSize()));
        personCSVReaderService.readPersonCSV(file, metadata);
    }
}

我可以使用Advanced Rest Client (ARC)或Postman来测试这个端点,方法是定义引用people.csv文件的“文件”部分和指定一些样例元数据JSON的文本部分。

一切正常,我得到了一个200状态,其中people.csv文件内容正在通过服务方法写入控制台输出:

代码语言:javascript
复制
uploading file people.csv of 256 bytes
{Address=1, City=2, Date of Birth=6, Name=0, Phone Number=5, State=3, Zipcode=4}
Person{name='John Brown', address='123 Main St.', city='Scottsdale', state='AZ', zipcode='85259', phoneNumber='555-1212', dateOfBirth='1965-01-01'}
Person{name='Jan Black', address='456 University Dr.', city='Atlanta', state='GA', zipcode='30306', phoneNumber='800-1111', dateOfBirth='1971-02-02'}
Person{name='Mary White', address='789 Possum Rd.', city='Nashville', state='TN', zipcode='37204', phoneNumber='888-2222', dateOfBirth='1980-03-03'}

现在,我想把它作为一个自动空手道测试来运行。我已经指定了一个MockConfig:

代码语言:javascript
复制
@Configuration
@EnableAutoConfiguration
@PropertySource("classpath:application.properties")
public class MockConfig {

    // Services ...
    @Bean
    public PersonCSVReaderService personCSVReaderService() {
        return new PersonCSVReaderService();
    }

    // Controllers ...
    @Bean
    public FileUploadController fileUploadController() {
        return new FileUploadController();
    }
}

我在类路径中也有一个MockSpringMvcServlet,我的karate config.js是:

代码语言:javascript
复制
function fn() {    
   var env = karate.env; // get system property 'karate.env'
   if (!env) {
      env = 'dev';
   }
   karate.log('karate.env system property was:', env);

   var config = {
     env: env,
     myVarName: 'someValue',
     baseUrl: 'http://localhost:8080'
   }

   if (env == 'dev') {
      var Factory = Java.type('MockSpringMvcServlet');
      karate.configure('httpClientInstance', Factory.getMock());
      //var result = karate.callSingle('classpath:demo/headers/common-noheaders.feature', config);
   } else if (env == 'stg') {
      // customize
   } else if (env == 'prod') {
      // customize
   }

   return config;
}

其他空手道测试使用mock servlet运行正常。

但是,当我尝试此测试来测试/document端点时:

代码语言:javascript
复制
Feature: file upload end-point

  Background:
    * url baseUrl
    * configure lowerCaseResponseHeaders = true

  Scenario: upload file
    Given path '/document'
    And header Content-Type = 'multipart/form-data'
    And multipart file file =  { read: 'people.csv', filename: 'people.csv', contentType: 'text/csv' }
    And multipart field metadata = { name: "joe", description: "stuff" }
    When method post
    Then status 200

我得到了这个错误:

代码语言:javascript
复制
16:14:42.674 [main] INFO  com.intuit.karate - karate.env system property was: dev 
16:14:42.718 [main] INFO  o.s.mock.web.MockServletContext - Initializing Spring DispatcherServlet ''
16:14:42.719 [main] INFO  o.s.web.servlet.DispatcherServlet - Initializing Servlet ''
16:14:43.668 [main] INFO  o.s.c.s.PostProcessorRegistrationDelegate$BeanPostProcessorChecker - Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$a4c7d08f] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
16:14:43.910 [main] INFO  o.h.validator.internal.util.Version - HV000001: Hibernate Validator 6.0.14.Final
16:14:44.483 [main] INFO  o.s.s.c.ThreadPoolTaskExecutor - Initializing ExecutorService 'applicationTaskExecutor'
16:14:44.968 [main] INFO  o.s.b.a.e.web.EndpointLinksResolver - Exposing 2 endpoint(s) beneath base path '/actuator'
16:14:45.006 [main] INFO  o.s.web.servlet.DispatcherServlet - Completed initialization in 2287 ms
16:14:45.066 [main] INFO  c.i.k.mock.servlet.MockHttpClient - making mock http client request: POST - http://localhost:8080/document
16:14:45.085 [main] DEBUG c.i.k.mock.servlet.MockHttpClient - 
1 > POST http://localhost:8080/document
1 > Content-Type: multipart/form-data

16:14:45.095 [main] ERROR com.intuit.karate - http request failed: null
file-upload.feature:13 - null
HTML report: (paste into browser to view) | Karate version: 0.9.2

我只能假设参数不符合我的终结点的预期-我从未在调试模式下进入终结点。

我试过这个:

代码语言:javascript
复制
    And multipart file file =  read('people.csv')
    And multipart field metadata = { name: "joe", description: "stuff" }

但这也是不可能的。

我做错了什么?people.csv与fileupload.feature在同一文件夹中,因此我假设它正在查找该文件。我还查看了这里给出的空手道演示项目中的upload.feature文件:

Karate demo project upload.feature

但我不能让它工作。感谢您的帮助。提前谢谢。

邮递员请求如下所示:

编辑更新:

我无法得到建议的答案。

以下是功能文件:

代码语言:javascript
复制
Feature: file upload

  Background:
    * url baseUrl
    * configure lowerCaseResponseHeaders = true

  Scenario: upload file
    Given path '/document'
    And header Content-Type = 'multipart/form-data'
    * def temp = karate.readAsString('people.csv')
    * print temp
    And multipart file file =  { value: '#(temp)', filename: 'people.csv', contentType: 'text/csv' }
    And multipart field metadata = { value: {name: 'joe', description: 'stuff'}, contentType: 'application/json' }
    When method post
    Then status 200

下面是运行该测试的控制台输出:

代码语言:javascript
复制
09:27:22.051 [main] INFO  com.intuit.karate - found scenario at line: 7 - ^upload file$
09:27:22.156 [main] INFO  com.intuit.karate - karate.env system property was: dev 
09:27:22.190 [main] INFO  o.s.mock.web.MockServletContext - Initializing Spring DispatcherServlet ''
09:27:22.190 [main] INFO  o.s.web.servlet.DispatcherServlet - Initializing Servlet ''
09:27:23.084 [main] INFO  o.s.c.s.PostProcessorRegistrationDelegate$BeanPostProcessorChecker - Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$a4c7d08f] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
09:27:23.327 [main] INFO  o.h.validator.internal.util.Version - HV000001: Hibernate Validator 6.0.14.Final
09:27:23.896 [main] INFO  o.s.s.c.ThreadPoolTaskExecutor - Initializing ExecutorService 'applicationTaskExecutor'
09:27:24.381 [main] INFO  o.s.b.a.e.web.EndpointLinksResolver - Exposing 2 endpoint(s) beneath base path '/actuator'
09:27:24.418 [main] INFO  o.s.web.servlet.DispatcherServlet - Completed initialization in 2228 ms
09:27:24.435 [main] INFO  com.intuit.karate - [print] Name,Address,City,State,Zipcode,Phone Number,Date of Birth
John Brown,123 Main St.,Scottsdale,AZ,85259,555-1212,1965-01-01
Jan Black,456 University Dr.,Atlanta,GA,30306,800-1111,1971-02-02
Mary White,789 Possum Rd.,Nashville,TN,37204,888-2222,1980-03-03

09:27:24.482 [main] INFO  c.i.k.mock.servlet.MockHttpClient - making mock http client request: POST - http://localhost:8080/document
09:27:24.500 [main] DEBUG c.i.k.mock.servlet.MockHttpClient - 
1 > POST http://localhost:8080/document
1 > Content-Type: multipart/form-data

09:27:24.510 [main] ERROR com.intuit.karate - http request failed: null
file-upload.feature:14 - null
HTML report: (paste into browser to view) | Karate version: 0.9.2

注意: people.csv文件读取成功并在控制台中打印。

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55640639

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档