I am trying to customize the extent report which is a third party reporting tool added to my cucumber framework where I want to customize the name of the report.html to "Outputfilename".html which I unable to do as the value of "Outputfilename " is coming from my config file.
here is my testrunner code
#RunWith(Cucumber.class)
#CucumberOptions(
features = ".//src//test//java//FeatureList",glue = "stepDefinations",
plugin = { "com.cucumber.listener.ExtentCucumberFormatter:target/cucumber-reports/"+Outputfilename+".html",
"junit:target/cucumber-results.xml"},
tags="#smoke",
monochrome = true
)
public class TestRunner {
private static final String Outputfilename = FileReader.getInstance().getConfigReader().getReportPath();
I would really appreciate your help.
Finally I fixed it-
So basically we need to change the runner class something like this-
package runners;
import PageObjectRep.CF;
import com.cucumber.listener.ExtentProperties;
import com.cucumber.listener.Reporter;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
import managers.FileReader;
import org.apache.log4j.PropertyConfigurator;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import java.io.File;
#RunWith(Cucumber.class)
#CucumberOptions(
features = ".//src//test//java//FeatureList",glue = "stepDefinations",
plugin = { "com.cucumber.listener.ExtentCucumberFormatter:",
"junit:target/cucumber-results.xml"},
tags="#test",
monochrome = true
)
public class TestRunner {
static String ReportName= CF.ReportName(); //function which creates file name as per the execution and saved in string.
#BeforeClass
public static void setup() {
ExtentProperties extentProperties = ExtentProperties.INSTANCE;
extentProperties.setReportPath("target/cucumber-reports/"+ReportName+".html"); //used same string name to create the file with the same name.
PropertyConfigurator.configure(".//src//log4j.properties");
}
Related
I am very new to JUnit and Mockito. I am trying to write a test case using JUnit and Mockito to verify log messages. I have 2 log messages in my code.
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public int run(final String[] args) throws Exception {
if (args.length != 2) {
log.info("Usage: input-path output-path");
log.info("Input and output path are required in the same sequence");
System.exit(1);
}
final String inputPath = args[0];
final String outputPath = args[1];
//some code
return 0;
}
The test case that I have written is
import org.apache.log4j.Appender;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.spi.LoggingEvent;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.verify;
#RunWith(MockitoJUnitRunner.class)
public class testRun {
#Mock
private Appender mockAppender;
#Before
public void setup() {LogManager.getRootLogger().addAppender(mockAppender);}
#After
public void teardown() {LogManager.getRootLogger().removeAppender(mockAppender);}
#Test
public void testValidArguments() {
//some code
Logger.getLogger(TryTest.class).info("Usage: input-path output-path");
Logger.getLogger(TryTest.class).info("Input and output path are required in the same sequence");
ArgumentCaptor<LoggingEvent> argument = ArgumentCaptor.forClass(LoggingEvent.class);
verify(appender,times(2)).doAppend(argument.capture());
assertEquals(Level.INFO, argument.getValue().getLevel());
assertEquals("Usage: input-path output-path", argument.getValue().getMessage());
assertEquals("Input and output path are required in the same sequence", argument.getValue().getMessage());
}
}
I have seen some solutions but they require to create another class which I do not want. Also while I execute the code it is taking the second value i.e., "Input and output path are required in the same sequence". The code executes fine if there is only one log message. I can put both the messages in one log.info if it cannot be solved. However, I do wish to know if there are any possible solution to this particular problem.
If you are using sl4j logger you could use ListAppender:
#Test
void test() {
Logger logger = (Logger) LogFactory.getLogger(YourClass.class);
ListAppender<ILoggingEvent> listAppender = new ListAppender<>();
listAppender.start();
logger.addAppender(listAppender);
YourClass yourClass = new YourClass();
yourClass.callYourMethodWithLogs();
List<ILoggingEvent> logsList = listAppender.list;
//make assertions with logList
}
I develop a test for the mobile application using Cucumber+Junit+Appium. When I try to run a test using cucumber and JUnit runner I receive: io.cucumber.junit.UndefinedStepException: The step "I install the application" is undefined. You can implement it using the snippet(s) below:
I tried some of the solutions from the medium blog and stack question, but this doesn't help.
I have a project structure:
src
|-main
|--java
|---{project-name}
|----config
|----models
|----screens
|----services
|-test
|--java
|---{project-name}
|----helpers
|----stepDefinitions
|-----LoginStep.java
|-----BaseStep.java
|-----LoginStep.java
|----RunCucumber.java
|--resources
|---feature
|----Login.feature
RunCucumber.java
package com.mobile.automation.framework;
import com.google.inject.Guice;
import com.mobile.automation.framework.module.ServiceModules;
import com.mobile.automation.framework.service.AppiumServer;
import com.mobile.automation.framework.config.drivers.DriverFactory;
import com.mobile.automation.framework.module.ScreensModule;
import io.appium.java_client.AppiumDriver;
import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
import org.junit.After;
import org.junit.Before;
import org.junit.runner.RunWith;
#RunWith(Cucumber.class)
#CucumberOptions(
strict = true,
monochrome = true,
glue = "src.test.java.com.mobile.automation.framework.stepDefinition",
features = "src/test/resources/feature",
plugin = {"pretty", "html:target/cucumber-report/cucumber.html",
"json:target/cucumber-report/cucumber.json",
"junit:target/cucumber-report/cucumber.xml"})
public class RunCucumber {
public static AppiumDriver driver;
#Before
public void setUpDriver() {
init();
new AppiumServer().startServer();
driver = new DriverFactory().getDriver();
}
#After
public void tearDownDriver() {
if (driver != null) {
driver.quit();
new AppiumServer().stopServer();
}
}
private void init() {
Guice.createInjector(
new ScreensModule(driver),
new ServiceModules(driver)
).injectMembers(this);
}
}
Login.feature
Feature: Sign In feature
Background:
Given I install application
And I enable all network activity
Then I am on Sign Page
Scenario: Sign In scenario
Given I am go to the Login Page
And I fill valid user data using "Config"
And I click sign in button
Then I am login in the application
LoginStep.java
package com.mobile.automation.framework.stepDefinition;
import javax.inject.Inject;
import com.mobile.automation.framework.config.ProjectConfig;
import com.mobile.automation.framework.models.User;
import com.mobile.automation.framework.screens.DashboardScreen;
import com.mobile.automation.framework.screens.SignInScreen;
import io.cucumber.java.ParameterType;
import io.cucumber.java.en.And;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
/**
* #author Tomash Gombosh
*/
public class LoginStep {
#Inject
private SignInScreen signInScreen;
#Inject
private DashboardScreen dashboardScreen;
#Given("^I am go to the Login Page$")
public void iAmGoToTheLoginPage() {
dashboardScreen.tapLogin();
}
#And("I fill valid user data using {string} {string}")
public void iFillValidUserDataUsing(String userName, String password) {
signInScreen.fillLogin(userName, password);
}
#And("I fill valid user data using {string}")
#ParameterType("Config")
public void iFillValidUserDataUsing() {
signInScreen.fillLogin(new User(data -> {
data.setEmail(new ProjectConfig().getBaseUser());
data.setPassword(new ProjectConfig().getBaseUserPassword());
}));
}
#And("I click sign in button")
public void iClickSignInButton() {
signInScreen.clickLogin();
}
#Then("I am login in the application")
public void iAmLoginInTheApplication() {
assertThat(signInScreen.isDisplayed()).isEqualTo(true);
}
}
Some of the steps on the Login class is missing, but that is because I want to put all the code to the question.
I expected to run that feature, but actually that is not work.
Typically src.test.java is not part of the package name. Try using:
glue = "com.mobile.automation.framework.stepDefinition",
And because Cucumber will search the runners package for glue by default can also remove the glue entirely.
New here myself working on Junit Runner, I agree with #M.P.Korstanje with classpath. Although I just had to change glue to refer the stepDefs with classpath too - wasn't getting recognized before.
So basically this is what I did to catch the necessary files to be triggered
feature = { "classpath:path-from-repo-root.feature" },
glue = { "classpath:reference-to-stepDef-folder" }
Bear in mind: for glue - I used to the reference to the folder containing the stepDefs and not the stepDef file itself. Hope this helps someone. Thanks
I have created an Event handler by following https://github.com/nateyolles/aem-osgi-annotation-demo/blob/master/core/src/main/java/com/nateyolles/aem/osgiannotationdemo/core/listeners/SampleOsgiResourceListener.java and it works fine. However, I get the warning "The field SlingConstants.TOPIC_RESOURCE_ADDED is deprecated". I did some searching and found this thread :https://forums.adobe.com/thread/2325819
Here are the challenges that I am facing:
1) I want to create a separate configuration interface for my event handler. I tried this and it isn't working
package com.aem.sites.interfaces;
import org.apache.sling.api.SlingConstants;
import org.osgi.service.event.EventConstants;
import org.osgi.service.metatype.annotations.AttributeDefinition;
import org.osgi.service.metatype.annotations.AttributeType;
import org.osgi.service.metatype.annotations.ObjectClassDefinition;
#ObjectClassDefinition(name = "Temperature Listener Configuration")
public #interface TemperatureListenerConfiguration {
#AttributeDefinition(
name = EventConstants.EVENT_FILTER,
description = "Configurable paths for temperature event listener",
type = AttributeType.STRING
)
String getPaths() default "/content/aemsite/en/jcr:content/root/responsivegrid/banner";
#AttributeDefinition(
name = EventConstants.EVENT_TOPIC,
description = "Event types",
type = AttributeType.STRING
)
String[] getEventTypes() default {SlingConstants.TOPIC_RESOURCE_ADDED,SlingConstants.TOPIC_RESOURCE_CHANGED, SlingConstants.TOPIC_RESOURCE_REMOVED};
}
package com.aem.sites.listeners;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Modified;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventHandler;
import org.osgi.service.metatype.annotations.Designate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.aem.sites.interfaces.TemperatureListenerConfiguration;
#Component(immediate=true,
service=EventHandler.class,
configurationPid = "com.aem.sites.listeners.EventHandler")
#Designate(ocd=TemperatureListenerConfiguration.class)
public class TemperaturePropertyListener implements EventHandler{
private final Logger logger = LoggerFactory.getLogger(getClass());
#Override
public void handleEvent(Event event) {
logger.info("*********************Event handler*****************************");
}
#Activate
#Modified
public void activate(TemperatureListenerConfiguration config) {
//config.getPaths();
logger.info("**************************TemperaturePropertyListener******************activate**********************");
}
}
I also want the solution for SlingConstants deprecated issue. Not sure if ResourceChangeListener is the answer to my problem and if yes then how everything is going to work together in the code.
Thanks in advance
===============================
Latest Code
package com.aem.sites.listeners;
import java.util.List;
import org.apache.sling.api.resource.observation.ResourceChange;
import org.apache.sling.api.resource.observation.ResourceChangeListener;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Modified;
import org.osgi.service.metatype.annotations.Designate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.aem.sites.interfaces.TemperatureListenerConfiguration;
#Component(immediate=true,
service=ResourceChangeListener.class,
configurationPid = "com.aem.sites.listeners.TemperaturePropertyListener")
#Designate(ocd=TemperatureListenerConfiguration.class)
public class TemperaturePropertyListener implements ResourceChangeListener{
private final Logger logger = LoggerFactory.getLogger(getClass());
#Override
public void onChange(List<ResourceChange> changes) {
for (final ResourceChange change : changes) {
logger.info("**************************TemperaturePropertyListener******************change type**********************"+change.getType());
}
}
#Activate
#Modified
public void activate(TemperatureListenerConfiguration config) {
//config.getPaths();
logger.info("**************************TemperaturePropertyListener******************activate**********************");
}
}
The Interface
package com.aem.sites.interfaces;
import org.apache.sling.api.resource.observation.ResourceChangeListener;
import org.osgi.service.metatype.annotations.AttributeDefinition;
import org.osgi.service.metatype.annotations.AttributeType;
import org.osgi.service.metatype.annotations.ObjectClassDefinition;
#ObjectClassDefinition(name = "Temperature Listener Configuration")
public #interface TemperatureListenerConfiguration {
#AttributeDefinition(
name = ResourceChangeListener.PATHS,
description = "Configurable paths for temperature event listener",
type = AttributeType.STRING
)
String[] getPaths() default {"/content/aemsite/en/jcr:content/root/responsivegrid/banner"};
#AttributeDefinition(
name = ResourceChangeListener.CHANGES,
description = "Event types",
type = AttributeType.STRING
)
String[] getEventTypes() default {"ADDED","REMOVED","CHANGED","PROVIDER_ADDED", "PROVIDER_REMOVED"};
}
Looking at the Javadoc for org.apache.sling.api.SlingConstants in sling 9 documentation here: http://sling.apache.org/apidocs/sling9/org/apache/sling/api/SlingConstants.html
it tells you specifically that TOPIC_RESOURCE_ADDED is deprecated:
Deprecated. Register a ResourceChangeListener instead
Read the documentation for ResourceChangeListener, additionally, you can take a look at a sample SCR service impl from ACS Samples:
It should not be hard to convert that to R6 declarative service.
Also, here are two examples from the sling project ResourceBackedPojoChangeMonitor and OsgiObservationBridge
Try to mimic those classes with the properties in the same class.
I'm trying to run JBoss remote in JUnit and I'm getting an error:
Caused by: java.lang.VerifyError: Cannot inherit from final class
Here is part of JUnit class with Remote:
import static org.junit.Assert.*;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.SessionManager;
public class Test1 {
private static SessionManager _service;
#BeforeClass
public static void doSms() throws Exception {
String JBOSS_CONTEXT = "org.jboss.naming.remote.client.InitialContextFactory";
Properties properties = new Properties();
properties.put(Context.INITIAL_CONTEXT_FACTORY, JBOSS_CONTEXT);
properties.put(Context.PROVIDER_URL, "remote://localhost:4447");
properties.put(Context.SECURITY_PRINCIPAL, "testuser");
properties.put(Context.SECURITY_CREDENTIALS, "testpassword");
_service = (SessionManager) new InitialContext(properties).lookup("java:global/SessionManager");
}
}
This error not belongs to JBoss Remote in JUnit.
Check all required jar placed in your class path.
Avoid conflicting between same jar with two versions(Don't add two different version jar).
I'm using JDepend to analyze my architecture and create structural tests to verify dependency within a Layered architecture. The two relevant layers are com.domain and com.infrastructure. Domain concretely depends on the Infrastructure layer.
Why is the following test failing?
import java.io.IOException;
import jdepend.framework.DependencyConstraint;
import jdepend.framework.JDepend;
import jdepend.framework.JavaPackage;
import junit.framework.TestCase;
public class DependencyTest extends TestCase {
private JDepend jdepend;
#Override
public void setUp() throws IOException {
jdepend = new JDepend();
jdepend.addDirectory("build/classes/com");
}
public void testDomainDependsOnInfastructure_ShouldBeTrue() {
DependencyConstraint constraint = new DependencyConstraint();
JavaPackage domainPackage = constraint.addPackage("com.domain");
JavaPackage infastructurePackage = constraint.addPackage("com.infrastructure");
domainPackage.dependsUpon(infastructurePackage);
jdepend.analyze();
assertEquals("Domain doesn't depend on Infrastructure layer", true, jdepend.dependencyMatch(constraint));
}
}
jdepend.analyze() returns the relevant packages, so I do know it is finding my code. Any ideas?
Figured it out. JDepend's match function checks all packages, including libraries. I had to custom load it with just the packages I wanted. Here's the code that resolved my problem, if anyone ever runs into this problem.
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import jdepend.framework.DependencyConstraint;
import jdepend.framework.JDepend;
import jdepend.framework.JavaPackage;
import junit.framework.TestCase;
public class DependencyTest extends TestCase {
private JDepend jdepend;
#Override
public void setUp() throws IOException {
jdepend = new JDepend();
jdepend.addDirectory("build/classes/com");
}
public void testDomainDependsOnInfastructure_ShouldBeTrue() {
DependencyConstraint constraint = new DependencyConstraint();
JavaPackage distribution = constraint.addPackage("com.distribution");
JavaPackage domainPackage = constraint.addPackage("com.domain");
JavaPackage infastructurePackage = constraint.addPackage("com.infrastructure");
distribution.dependsUpon(domainPackage);
domainPackage.dependsUpon(infastructurePackage);
jdepend.analyze();
Collection<JavaPackage> actual = new ArrayList<JavaPackage>();
actual.add(domainPackage);
actual.add(distribution);
actual.add(infastructurePackage);
assertEquals("Domain doesn't depend on Infrastructure layer", true, constraint.match(actual));
}
}