简体   繁体   English

Apache Camel:文件和 http 组件的单元测试

[英]Apache Camel: Unit testing for file and http components

I am fairly new to Camel & just managed to implement a use case as below with 2 routes which is using file & http components.我对 Camel 还很陌生,只是设法实现了一个如下用例,其中有 2 条使用文件和 http 组件的路由。 Looking for some leads on writing junits for the same.寻找一些关于编写junits的线索。 Have tried some sample test case below based on the inputs that i found on the net.根据我在网上找到的输入,我尝试了下面的一些示例测试用例。 Not sure if that suffices.不确定这是否足够。 Appreciate your help!感谢你的帮助!

  • Implementation:执行:

     @Override public void configure() throws Exception { // Global Exception Handling block onException(FileWatcherException.class).process(new Processor() { public void process(Exchange exchange) throws Exception { System.out.println("Exception handled"); } }).to("file:C:/error?recursive=true").handled(true); // Actively listen to the input folder for an incoming file from("file:C:/input?noop=true&recursive=true&delete=true").process(new Processor() { public void process(Exchange exchange) throws Exception { String fileName = exchange.getIn().getHeader("CamelFileName").toString(); exchange.getIn().setHeader("fileName", fileName); } }) // Call the Get endpoint with fileName as input parameter.setHeader(Exchange.HTTP_METHOD, simple("GET")).toD("http://localhost:8090/fileWatcher?fileName=${header.fileName}").choice() // if the API returns true, move the file to the outbox folder.when(header(Exchange.HTTP_RESPONSE_CODE).isEqualTo(constant(200))).to("file:C:/outbox?noop=true&recursive=true").endChoice() // If the API's response code is other than 200, move the file to error folder.otherwise().log("Moving the file to error folder").to("file:C:/error?recursive=true").end(); // Listen to the outbox folder for file arrival after it gets moved in the above step from("file:C:/outbox?noop=true&recursive=true") // Request Body for POST call is set in FileDetailsProcessor class.process(new FileDetailsProcessor()).marshal(jsonDataFormat).setHeader(Exchange.HTTP_METHOD, simple("POST")).setHeader(Exchange.CONTENT_TYPE, constant("application/json")) // Call the Rest endpoint with fileName & filePath as RequestBody.to("http://localhost:8090/fileWatcher").process(new MyProcessor()).end(); }
  • Junit Junit

     @Test public void checkFileWatcherFunctionality() throws Exception { context.getRouteDefinitions().get(0).adviceWith(context, new AdviceWithRouteBuilder() { @Override public void configure() throws Exception { // mocking all endpoints. **QUESTION** - Is this required? mockEndpointsAndSkip("http://localhost:8090:fileWatcher?fileName=loan.csv"); mockEndpointsAndSkip("file:C:/processing"); mockEndpointsAndSkip("file:C:/error"); mockEndpointsAndSkip("http://localhost:8090:fileWatcher"); } }); context.start(); // **QUESTION** - This is a GET call. Expecting only the HTTP status code from it. How to check that? getMockEndpoint("mock:http://localhost:8090:fileWatcher?fileName=abc.txt").expectedBodyReceived(); // **QUESTION** - This is a POST call. How to send request body along? Expecting only the HTTP status code from it. How to check that? getMockEndpoint("mock:http://localhost:8090:fileWatcher").expectedBodyReceived(); // **QUESTION** - Is this the right way to check? getMockEndpoint("mock:file:C:/processing").expectedFileExists("loan.csv");; template.sendBodyAndHeader("file:C:/inbound", "", Exchange.FILE_NAME, "loan.csv"); // QUESTION - What can be asserted now?

    } }

Also - How to write test cases for negative flow (exception scenario)?另外-如何为负流(异常情况)编写测试用例? Looking for suggestions.寻找建议。

I have managed to draft the test case.我已经设法起草了测试用例。 Is this the right approach or can there be a better way?这是正确的方法还是有更好的方法? This might be more of an integration test i suppose.我想这可能更像是一个集成测试。

The issue i see now is that the test case doesn't report at the end (success or failure), instead it keeps waiting for file arrival in the input folder.我现在看到的问题是测试用例最后没有报告(成功或失败),而是一直等待文件到达输入文件夹。 What am i missing?我错过了什么?

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class FileWatcherRouteBuilderTest extends CamelTestSupport {

    @Autowired
    private TestRestTemplate restTemplate;
    
    @Override
    public RoutesBuilder createRouteBuilder() throws Exception {
        return new FileWatcherRouteBuilder();
    }

    @Test
    public void testFileCopy() throws Exception {
        template.sendBodyAndHeader("file:C:/inbound", "", Exchange.FILE_NAME, "abc.csv");
        
        // Call the GET endpoint 
        ResponseEntity<String> getResponse = restTemplate.getForEntity("http:localhost:8090/fileWatcher?fileName=abc.csv",
                String.class);
        assertTrue("Get call is unsuccessful", getResponse.getStatusCode().is2xxSuccessful());
        String response = getResponse.getBody();
        assertTrue(!response.isEmpty());
        
        // The file would have moved to output folder now.
        File targetFile = new File("C:/processing");
        assertTrue(targetFile.isDirectory());
        assertEquals(1, targetFile.listFiles().length);
        
        // Since we need to extract the file name, doing the below step
        Exchange exchange = consumer.receive("file:C:/processing");
        String fileName = exchange.getIn().getHeader("CamleFileName").toString();
        // RequestBody needed for POST call
        FileDetails fileDetails = new FileDetails(fileName, "C:/processing/"+fileName);
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<FileDetails> request = new HttpEntity<FileDetails>(fileDetails, headers);
        // Call the POST endpoint
        ResponseEntity<String> postResponse = restTemplate.postForEntity("http://localhost:8090/fileWatcher", request, String.class);
        assertTrue("Post call is unsuccessful", postResponse.getStatusCode().is2xxSuccessful());
        
        // Asserting that after both the web service calls, the file is still available in the output folder
        assertEquals(1, targetFile.listFiles().length);
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM