Skip to content

JUnit4 callback reporting example

Ihar Kahadouski edited this page Feb 27, 2020 · 6 revisions

JUnit4 callback reporting example

Usage of callback reporting is represented in this test class.

Basic steps to use callback reporting feature in your test classes:

Define storage for TestItemLeaf instances (List, Map, etc.):

    private static List<TestItemTree.TestItemLeaf> testItemLeaves = new ArrayList<TestItemTree.TestItemLeaf>();

Define JUnit rule to intercept test-method finish event and create TestItemLeaf from provided Description using ItemTreeUtils util:

    @Rule
    public TestRule rule = new TestWatcher() {
 		@Override
 		protected void finished(Description description) {
 			TestItemTree.TestItemLeaf testItemLeaf = ItemTreeUtils.retrieveLeaf(description, ITEM_TREE);
 			if (testItemLeaf != null) {
				testItemLeaves.add(testItemLeaf);
 			}

  		}
 	};

Define JUnit @AfterClass method and apply your logic to required TestItemLeaf:

    @AfterClass
    public static void afterClass() {
		attachLog();
		changeStatus();
	}

Send Log using ItemTreeReporter sendLog method:

    private static void attachLog() {
		ItemTreeReporter.sendLog(REPORT_PORTAL.getClient(),
				"ERROR",
				"Error message",
				Calendar.getInstance().getTime(),
				testItemLeaves.get(0)
		);
	}

Send finish request for TestItem using ItemTreeReporter finishItem method:

    private static void changeStatus() {
		FinishTestItemRQ finishTestItemRQ = new FinishTestItemRQ();
		finishTestItemRQ.setStatus("FAILED");
		finishTestItemRQ.setEndTime(Calendar.getInstance().getTime());
		ItemTreeReporter.finishItem(REPORT_PORTAL.getClient(), finishTestItemRQ, ITEM_TREE.getLaunchId(), testItemLeaves.get(0))
				.cache()
				.ignoreElement()
				.blockingAwait();
	}

Adding attributes (Saucelabs job id)

private static void addSaucelabsAttribute() {
		FinishTestItemRQ request = new FinishTestItemRQ();
		request.setEndTime(Calendar.getInstance().getTime());
		request.setStatus("PASSED");
		request.setAttributes(Sets.newHashSet(new ItemAttributesRQ("SLID", "0586c1c90fcd4a499591109692426d54")));
		ItemTreeReporter.finishItem(REPORT_PORTAL.getClient(), request, ITEM_TREE.getLaunchId(), testItemLeaves.get(0))
				.cache()
				.ignoreElement()
				.blockingAwait();
	}

TestItem finish method returns Maybe<String> so you should either provide consumer for result or use blockingAwait to provide request sending before test run finish (application termination).