JUnit: Is there a RunListener method, which is called after #After annotated method? - testing

Is there a way to invoke a method after all #After annotated methods of a test method had been run?
I need this for a special framework for my company.
In testng i can use the afterInvocation method, which is called after every configuration method. Is there some alternative in JUnit?

A rule will run after all the #Afters. The ExternalResource could be abused in order to do what you want:
public class VerifyTest {
#Rule public ExternalResource externalResource = new ExternalResource() {
public void after() {
System.out.println("ExternalResource.after");
}
};
#After
public void after1() {
System.out.println("after1");
}
#After
public void after2() {
System.out.println("after2");
}
#Test
public void testVerify throws IOException {
}
}

Related

JUnit5 afterAll callback fires at the end of each test class and not after all tests

I have 15 JUnit5 classes with tests. When I run them all from maven, the afterAll() is executed 15 times which causes 15 notifications to a Slack Webhook. Is there anything else I need to only send one notification?
public class TestResultsExtensionForJUnit5 implements TestWatcher, AfterAllCallback {
#Override
public void afterAll(ExtensionContext extensionContext) throws Exception {
sendResultToWebHook();
}
#Override
public void testDisabled(ExtensionContext context, Optional<String> reason) {
totalTestDisabled = totalTestDisabled + 1;
}
#Override
public void testSuccessful(ExtensionContext context) {
totalTestPassed = totalTestPassed + 1;
}
#Override
public void testAborted(ExtensionContext context, Throwable cause) {
totalTestAborted = totalTestAborted + 1;
}
#Override
public void testFailed(ExtensionContext context, Throwable cause) {
totalTestFailed = totalTestFailed + 1;
}
}
#ExtendWith(TestResultsExtensionForJUnit5.class)
public class Random1Test {}
The best way is to implement and install a TestExecutionListener from the JUnit Platform, as it is described in the User Guide at https://junit.org/junit5/docs/current/user-guide/#launcher-api-listeners-custom -- override the default testPlanExecutionFinished​(TestPlan testPlan) method with your notifying call. Here, all tests from all engines are finished.

Where do Before and After hooks go in Cucumber

I have a fairly simple Cucumber test framework with a feature file, a step definitions file, and a test runner class that looks like this:
#RunWith(Cucumber.class)
#CucumberOptions(features = "src/test/java/com/tests/cucumber/features/ui/ExampleTest.feature",
glue = { "com.tests.cucumber.stepdefinitions" },
)
public class ExampleTestRunner {
}
This runs a scenario in the feature file just fine. Now I want to add a Before and After hook to do some setup and teardown, but I can't for the like of me get the hooks to run. I've tried adding the hooks to the ExampleTestRunner and to the StepDefinition class, but they never run. Where should I put these hooks? At the moment, the hooks just look like this, but I'll add content to them once I've worked this out!
package com.tests.cucumber.stepdefinitions;
import cucumber.api.java.After;
import cucumber.api.java.Before;
public class StepDefinitions {
#Before
public void before() {
System.out.println("starting before()");
}
}
Thanks for any help.
I am a little hesitant to answer this question even though I managed to get this to work. As far as I can tell, the problem was that I had added the Before and After methods in classes that were extended by other classes. In this situation, the tests would not run. I had to add the Before and After methods to a class that was not extended.
It feels like this is similar to the situation in which if you specify a step definition in a class that is extended by another class, then the step definition is considered to have a duplicate definition. Do I have the correct diagnosis here?
I use like this;
Runner Class:
#RunWith(Cucumber.class)
#CucumberOptions(
features = {"src\\test\\features\\ui_features"},
glue = {"com\\base\\tm\\auto_reg\\tests\\ui_tests\\price_features"},
plugin = {"com.cucumber.listener.ExtentCucumberFormatter:"}
)
public class PriceFeatureRunner {
#BeforeClass
public static void setup() {
RunnerUtil.setup(PriceFeatureRunner.class);
}
#AfterClass
public static void teardown() {
RunnerUtil.teardown();
}
}
RunnerUtil.java:
public class RunnerUtil {
public static void setup(Class<?> clazz) {
String reportPath = "target/cucumber-reports/" + clazz.getSimpleName().split("_")[0] + "_report.html";
ExtentProperties extentProperties = ExtentProperties.INSTANCE;
extentProperties.setReportPath(reportPath);
}
public static void teardown() {
UiHooks uiHooks = new UiHooks();
uiHooks.afterScenario();
ExtentReportConfiguration.configureExtentReportTeardown();
}
}
UiHooks.java
public class UiHooks implements HookHelper {
public static final String BASE_URL = "https://www.stackoverfow.com/";
private Scenario scenario;
#Override
#Before
public void beforeScenario(Scenario scenario) {
this.scenario = scenario;
Reporter.assignAuthor(System.getProperty("user.name"));
}
#Override
#After
public void afterScenario() {
if (HookUtil.driver != null) {
HookUtil.driver.quit();
}
if (HookUtil.seleniumBase != null) {
HookUtil.seleniumBase.stopService();
}
}
#Override
#After
public void afterTest() {
if (HookUtil.driver != null) {
HookUtil.driver.quit();
}
if (HookUtil.seleniumBase != null) {
HookUtil.seleniumBase.stopService();
}
}
}
HookHelper.Java
public interface HookHelper {
#Before
void beforeScenario(Scenario scenario);
#After
void afterScenario();
void afterTest();
}

AxonFramework: How to test #EventHandler

I have this component which integrates with other services through a RabbitMQ queue:
#Component
#ProcessingGroup("amqpProcessor")
public class ExternalEventsHandler {
#EventHandler
public void on(SomeOtherServiceEvent event) {
// Dispatches some command
}
}
How should I test this?
#Test
public void shouldReactToSomeOtherServiceEvent() {
//TODO
}
The best way is just to instantiate or inject your event handler class in the unit test, instantiate a test event, and simply call the method. Something like this:
#Mock
private FooRepository fooRepository;
private FooEventHandler fooEventHandler;
#Before
public void before() {
fooEventHandler = new FooEventHandler(fooRepository);
}
#Test
public void createFoo() {
fooEventHandler.createFoo(new FooCreatedEvent("fooId");
ArgumentCaptor<Foo> argument = ArgumentCaptor.forClass(Foo.class);
verify(fooRepository, times(1)).save(argument.capture());
assertTrue(argument.getValue().getId(), "fooId"));
}

How to run a TestNG class from another class

Hi When i run the following testNG file as a standalone script if executes as expected.
public class TESTTNGClass {
WebDriver driver;
#Test
public void f() {
System.out.println("In Test");
}
#BeforeMethod
public void beforeMethod() {
System.out.println("Before Test");
}
#AfterMethod
public void afterMethod() {
System.out.println("After Test");
}
}
O/P:
Before Test
In Test
After Test
But why does the same not work when called from another class. Please help to achieve the same when triggered from another class. Following is the class calling the test class
public class TESTClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
TESTTNGClass t = new TESTTNGClass();
t.f();
}
}
O/P:
In Test
Here is the Answer to your Question:
In the process of understanding and experiment with Java & TestNG you have diminished the Annotation power of TestNG.
When you are executing TESTTNGClass.java as a TestNG Test all works well. No issues.
When you are executing TESTClass.java as a Java Application, Java only understands main() where you are creating an object of Class TESTTNGClass and then you are calling the method f(). As Java Compiler have have no idea of BeforeMethod, Test & AfterMethod Annotations of TestNG, it simply executes f() method, prints In Test and ends execution.
About how to do it:
Replace main() by some other name foo().
Bring f() from "TESTTNGClass" class into "TESTClass" class.
While you write "TESTClass" class extend "TESTTNGClass" class.
Execute "TESTClass.java" as a TestNG Test
Your Application will look like:
TESTTNGClass Class:
package Q44240531_TestNG_Main;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
public class TESTTNGClass
{
#BeforeMethod
public void beforeMethod() {
System.out.println("Before Test");
}
#AfterMethod
public void afterMethod() {
System.out.println("After Test");
}
}
TESTClass Class:
package Q44240531_TestNG_Main;
import org.testng.annotations.Test;
public class TESTClass extends TESTTNGClass {
#Test
public void f()
{
System.out.println("In Test");
}
}
Let me know if this Answers your Question.
public class TESTClass extends TESTTNGClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
TESTTNGClass t = new TESTTNGClass();
try{
t.f();
}catch (Exception e){
e.printStackTrace();
}
}
}

Get the name of currently executing #Test method name in #BeforeMethod and #AfterMethod in testng

I want to Print the name of Currently Executing Test Method in #BeforeMethod and #AfterMethod using testng.
Like :
public class LoginTest {
#Test
public void Test01_LoginPage(){
//Some Code here
}
#Test
public void Test02_LoginPage(){
//Some Code Here
}
#BeforeMethod
public void beforeTestCase(){
//Print Test method name which is going to execute.
}
#AfterMethod
public void AfterTestCase(){
//Print Test method name which is executed.
}
}
From the documentation:
public class LoginTest {
#Test
public void Test01_LoginPage() {
//Some Code here
}
#Test
public void Test02_LoginPage() {
//Some Code Here
}
#BeforeMethod
public void beforeTestCase(Method m) {
System.out.println(m.getName());
}
#AfterMethod
public void AfterTestCase(Method m) {
System.out.println(m.getName());
}
}
You can use listeners like this link. Important code from the link:-
// This belongs to IInvokedMethodListener and will execute before every method including //#Before #After #Test
public void beforeInvocation(IInvokedMethod arg0, ITestResult arg1) {
String textMsg = "About to begin executing following method : " + returnMethodName(arg0.getTestMethod());
Reporter.log(textMsg, true);
}
// This belongs to IInvokedMethodListener and will execute after every method including #Before #After #Test
public void afterInvocation(IInvokedMethod arg0, ITestResult arg1) {
String textMsg = "Completed executing following method : " + returnMethodName(arg0.getTestMethod());
Reporter.log(textMsg, true);
}
// This will return method names to the calling function
private String returnMethodName(ITestNGMethod method) {
return method.getRealClass().getSimpleName() + "." + method.getMethodName();
}
The below example explains how you can get the method name and class name of your #test method in before method and After method
#Test
public void exampleTest(){
}
#BeforeMethod
public void beforemethod(Method method){
//if you want to get the class name in before method
String classname = getClass().getSimpleName();
//IF you want to get the method name in the before method
String methodName = method.getName()
//this will return you exampleTest
}
#AfterMethod
public void beforemethod(Method method){
//if you want to get the class name in After method
String classname = getClass().getSimpleName();
//IF you want to get the method name in the After method
String methodName = method.getName()
//this will return you exampleTest
}