Nifi初探 - 如何測試Nifi Processor

之前的博客簡單講了一下如何去定義一個簡單的Json處理Processor,這一次是在無數次測試中總算厭煩了把打包好的Nar包上傳到lib中,然後重啓服務器,然後再測試功能,測試的時候還很難看到日誌...

同樣搬運自 - > nifi.rock

對自定義開發的Processor進行Unit Test

開始

Apache Nifi框架的單元測試是基於Junit的test runners的,在他們的代碼中有一些實例,現在根據我們自己的項目進行單元測試,應該會更感同身受一點。
在這一階段,我們會將單元測試功能加入我們之前創建的JsonProcessor中。

準備工作

我們需要將之前的工程git下來,如果你沒看我之前的文章,可以在這裏 找到並git下來。
我們的Processor Java代碼位於sha0w.pub.jsonNifi.processors這個包下,同樣的,測試文件就應該在test\java目錄對應的位置下。

然後我們需要在maven中添加nifi對應的依賴

<dependency>
    <groupId>org.apache.nifi</groupId>
    <artifactId>nifi-mock</artifactId>
    <version>${nifi.version}</version>
    <scope>test</scope>
</dependency>

這裏我們採用nifi-mock以及一般都會帶上的junit依賴來進行單元測試,同樣的,在之後如果有機會的話,我也會將我是用Mockito和JUnit進行單元測試的方法分享給大家(當然原文作者挖的這個坑並沒有填上)。

在我們的測試中,有幾個org.apache.nifi.utils包是需要被import的,比如TestRunnerTestRunnersMockFlowFile這三個類。

當然我們也需要在測試方法上添加@Test標籤,在添加了這個JUnit 標籤後,你就可以在方法中去初始化Nifi提供的TestRunner等組件了。

我們需要去創建一個TestRunner類,然後把我們的Processor傳給它,接着對其的PropertiesDescription進行傳值,然後爲了測試我們的JsonProcessor,我們使用一個ByteArrayInputStream當作傳遞的Flow File,同樣的,你也可以使用一個本地的json文件作爲資源文件。

當一個test runner創建時,使用runner.setProperties(PropertyDescriptor)以及runner.enqueue(content)進行值賦予。然後使用一些斷言進行單元測試,測試結果情況。

Nifi簡化了使用斷言進行FlowFile測試的複雜度,你可以通過Transfered方法傳遞的Relationship以及獲取FlowFile等進行斷言測試,具體的代碼如下:

@org.junit.Test
public void testOnTrigger() throws IOException {
    // Content to be mock a json file
    InputStream content = new ByteArrayInputStream("{\"hello\":\"nifi rocks\"}".getBytes());

    // Generate a test runner to mock a processor in a flow
    TestRunner runner = TestRunners.newTestRunner(new JsonProcessor());

    // Add properites
    runner.setProperty(JsonProcessor.JSON_PATH, "$.hello");

    // Add the content to the runner
    runner.enqueue(content);

    // Run the enqueued content, it also takes an int = number of contents queued
    runner.run(1);

    // All results were processed with out failure
    runner.assertQueueEmpty();

    // If you need to read or do aditional tests on results you can access the content
    List<MockFlowFile> results = runner.getFlowFilesForRelationship(JsonProcessor.SUCCESS);
    assertTrue("1 match", results.size() == 1);
    MockFlowFile result = results.get(0);
    String resultValue = new String(runner.getContentAsByteArray(result));
    System.out.println("Match: " + IOUtils.toString(runner.getContentAsByteArray(result)));

    // Test attributes and content
    result.assertAttributeEquals(JsonProcessor.MATCH_ATTR, "nifi rocks");
    result.assertContentEquals("nifi rocks");
}

這部分就是測試onTrigger方法的@test方法。
之後有機會將會簡介如何不使用Nifi自帶的TestRunner,使用Mockito以及JUnit進行對Nifi的測試。(然而好像並沒有之後的教程了)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章