Karate:如何测试多部分表单数据端点?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (66)

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

@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文件内容被服务方法写入控制台输出:

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'}

现在,我想将其作为自动Karate测试来运行。我已经指定了一个MockConfig:

@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是:

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;
}

其他Karate测试使用模拟servlet运行正常。

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

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

我收到此错误:

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

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

我试过这个:

    And multipart file file =  read('people.csv')
    And multipart field metadata = { name: "joe", description: "stuff" }

但这也不是首发。

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

Karate演示项目upload.feature

但我无法使其发挥作用。任何帮助赞赏。提前致谢。

提问于
用户回答回答于

请参阅文档的这一部分:https//github.com/intuit/karate#read-file-as-string

所以做这个改变:

* def temp = karate.readAsString('people.csv')
And multipart file file =  { read: '#(temp)', filename: 'people.csv', contentType: 'text/csv' }

扫码关注云+社区

领取腾讯云代金券