Facing issue while using #Factory and #dataprovider in Testng - selenium

1. Could you please help me, looks like #factory, #dataProvider and
#dependsOn not working properly, here i have two inputs Client A and
Client B but i am only able to get only Client B not able to get the
Client A, looks like few methods are unreachable while executing,
really need help, How to handle this kind of issue
Below is my testNg.xml
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Suite1" group-by-instances="true" verbose="1">
<parameter name="suit-param" value="This is at suite level"></parameter>
<test name="Test1">
<classes>
<class name="com.brcc.tool.Rm_Saa.RmUi"/>
</classes>
</test>
</suite>
Config class
public class DriverConfig {
public WebDriver driver;
public Properties prop = new Properties();
#BeforeSuite
public void setUp() throws IOException {
System.setProperty("webdriver.gecko.driver","drivers/geckodriver.exe");
driver = new FirefoxDriver();
FileInputStream ip = new FileInputStream(
"config.properties");
prop.load(ip);
driver.navigate().to(prop.getProperty("RmUrl"));
}
}
Below Is my testNg code
package com.brcc.tool.Rm_Saa;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.io.FileWriter;
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
import com.brcc.tool.Configuration.DriverConfig;
import com.brcc.tool.Configuration.SftpConn;
public class RmUi extends DriverConfig {
WebDriverWait wait;
private String data;
#BeforeSuite
public void beforeClass() throws Exception{
wait = new WebDriverWait(driver,60);
System.out.println("Before Test case");
}
#DataProvider
public static Iterator<Object[]> getTestData() throws Exception {
ArrayList<Object[]> getclientProduct = new ArrayList<Object[]>();
Object[] obj1 = {"Client A"};
Object[] obj2 = {"Client B"};
getclientProduct.add(obj1);
getclientProduct.add(obj2);
return getclientProduct.iterator();
}
#Factory(dataProvider = "getTestData")
public RmUi(String s) {
this.data = s;
}
#Test(priority = 1)
public void getTest() throws Exception {
System.out.println("login");
System.out.println("Client in Login = "+data);
// Next Test case later create a new test case and put below code
}
#Test(priority = 2,dependsOnMethods="getTest")
public void getRmApp() throws Exception {
System.out.println("getRmApp = "+data);
}
#Test(priority = 3,dependsOnMethods="getRmApp")
public void radioButton() throws Exception {
wait = new WebDriverWait(driver, 10);
System.out.println("radioButton ="+data);
}
#Test(priority = 4,retryAnalyzer = com.brcc.tool.RetryFailedTestCases.RetryTestCases.class,dependsOnMethods="radioButton")
public void clickOutputbatch()
{
System.out.println("clieckOutputbatch ="+data);
}
#Test(priority = 5,dependsOnMethods="clickOutputbatch")
public void getbatchReleaseStatus() throws Exception {
System.out.println("getbatchReleaseStatus ="+data);
System.out.println("_______________________________________________");
}
}
My Actual output
Before Test case
login
Client in Login = Client B
getRmApp = Client B
radioButton =Client B
clieckOutputbatch =Client B
getbatchReleaseStatus =Client B
_______________________________________________
login
Client in Login = Client A
getRmApp = Client A
radioButton =Client A
clieckOutputbatch =Client A
getbatchReleaseStatus =Client A
My Expected output
Before Test case
login
Client in Login = Client B
getRmApp = Client B
radioButton =Client B
clieckOutputbatch =Client B
getbatchReleaseStatus =Client B
_______________________________________________
login
Client in Login = Client A
getRmApp = Client A

After looking at the code you shared, I can confirm that the issue is present in your test code.
In your class DriverConfig you are instantiating a WebDriver object within a #BeforeSuite annotated method. #BeforeSuite by definition is meant to be executed only once per <suite> tag. What this means is that if your factory ended up producing two instances, the driver object would be instantiated ONLY for one of the instances and for the other one it would be null.
You are coupling this with a WebDriverWait that is perhaps taking in a null driver instance.
To fix this, you would need to get rid of your #BeforeSuite and replace it with #BeforeClass annotation. Here the assumption is that
you would like the same webdriver instance to be shared by multiple #Test methods in the same class.
your #Test methods in the same test class (of which your #Factory is producing instances) do not open up individual websites and work on it but instead try to operate on the same website.
your #Test methods in the test class, will NOT run in parallel, because if they do, then your tests will fail because multiple #Test methods are now going to be sharing the same WebDriver instance.
If you are keen on doing thread safe concurrent parallel executions wherein
Every #Test method is a standalone entity by itself and does things only within itself.
You would like all your #Test methods to be able to run in parallel,
then take a look at this library that I built for this very exact purpose
https://github.com/RationaleEmotions/autospawn

Related

unable to replace karate,#cucumber options durin testcase migration from junit4 to junit5

Im using the below structure in testcases for junit4, now im migration to junit5 couldnt find a way to replace, please help.
#RunWith(Karate.class)
#CucumberOptions(
junit = {..},
features = "..",
plugin = {"..."},
glue = {"..."},
tags = {"...."})
Aaccording to junit5 #RunWith should be replace with #Extendwith but when i used #ExtendWith(karate.class) its giving error.
my testclass:
import KarateTest.utils.WiremockRunner;
import com.intuit.karate.junit4.Karate;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Disabled;
#Disabled
#RunWith(Karate.class)
#CucumberOptions(
junit = {".."},
features = "...",
plugin = {"..."},
glue = {"s.."},
tags = {"..", "...", "..","..."})
public class HT {
private static final WiremockRunner wiremock = new WiremockRunner();
#BeforeAll
public static void beforeClass() throws Exception {
wiremock.startWiremock();
Application.main(new String[] {"--spring.profiles.active=sb-vk"});
}
#AfterAll
public static void tearDown() throws Exception {
wiremock.stopWiremock();
}
}
There is no such thing as #CucumberOptions any more.
The recommendation is to use the Runner class, where you have full control to set the various options.
Refer to the examples: https://github.com/karatelabs/karate#junit-5-parallel-execution
import com.intuit.karate.Results;
import com.intuit.karate.Runner;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class TestParallel {
#Test
void testParallel() {
Results results = Runner.path("classpath:animals").tags("~#skipme").parallel(5);
assertEquals(0, results.getFailCount(), results.getErrorMessages());
}
}
For some related information, refer: https://stackoverflow.com/a/65578167/143475

How to read xml file key value using netflix archaius API?

I am new in Netflix Archaius. Can anyone please provide sample code to read key value from xml file ?
Also would like to see values are update automatically when I changed any key in XML file ...
Regards,
Ashish
Sample JUnit on how to use xml for key/value pairs and using Archaius to automatically load the changes :
Important note on the sample code : The program exits after the first callback. If you want to test more callbacks, increase the counter at class variable 'latch'
package com.test.config;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import org.apache.commons.configuration.XMLPropertiesConfiguration;
import org.junit.Test;
import com.netflix.config.AbstractPollingScheduler;
import com.netflix.config.ConcurrentMapConfiguration;
import com.netflix.config.ConfigurationManager;
import com.netflix.config.DynamicConfiguration;
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.config.DynamicStringProperty;
import com.netflix.config.FixedDelayPollingScheduler;
import com.netflix.config.PollResult;
import com.netflix.config.PolledConfigurationSource;
public class TestArchaius {
CountDownLatch latch = new CountDownLatch(1);
#Test
public void tes() throws Exception {
AbstractPollingScheduler scheduler = new FixedDelayPollingScheduler(0, 1000, false);
DynamicConfiguration dynamicConfiguration = new DynamicConfiguration(new MyPolledConfigurationSource(), scheduler);
ConfigurationManager.install(dynamicConfiguration);
DynamicStringProperty fieldsProperty = DynamicPropertyFactory.getInstance().getStringProperty("key1", "");
fieldsProperty.addCallback(() -> {
System.out.println(fieldsProperty.get());
latch.countDown();
});
latch.await();
}
class MyPolledConfigurationSource implements PolledConfigurationSource {
#Override
public PollResult poll(boolean initial, Object checkPoint) throws Exception {
ConcurrentMapConfiguration configFromPropertiesFile = new ConcurrentMapConfiguration(
new XMLPropertiesConfiguration("test.xml"));
Map<String, Object> fullProperties = new HashMap<String, Object>();
configFromPropertiesFile.getProperties().forEach((k, v) -> fullProperties.put((String) k, v));
return PollResult.createFull(fullProperties);
}
}
}
test.xml :
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>Description of the property list</comment>
<entry key="key1">value1</entry>
<entry key="key2">value2</entry>
<entry key="key3">value3</entry>
</properties>

HSQLDB inmemory mode doesn't delete files on shutdown

I'm using HSQLDB version 2.2.9 for testing purposes.
When I create named in memory database, files aren't deleted after calling shutdown function. On my filesystem I have folder DBname.tmp and files DBname.lck, DBname.log, DBname.properties and DBname.script. As I understand documentation (http://hsqldb.org/doc/2.0/guide/dbproperties-chapt.html#dpc_connection_url) it shouldn't happened.
For testing I'm using the following code:
import java.io.IOException;
import org.hsqldb.Server;
import org.hsqldb.persist.HsqlProperties;
import org.hsqldb.server.ServerAcl.AclFormatException;
import org.junit.Test;
public class HSQLDBInMemTest {
#Test
public void test() throws IOException, AclFormatException {
HsqlProperties props = new HsqlProperties();
props.setProperty("server.database.0", "test1");
props.setProperty("server.dbname.0", "test1");
props.setProperty("server.database.1", "test2");
props.setProperty("server.dbname.1", "test2");
Server hsqlServer = new Server();
hsqlServer.setRestartOnShutdown(false);
hsqlServer.setNoSystemExit(true);
hsqlServer.setProperties(props);
hsqlServer.start();
hsqlServer.shutdown();
}
}
Answered here: http://sourceforge.net/mailarchive/message.php?msg_id=30881908 by fredt
The code should look like:
import java.io.IOException;
import org.hsqldb.Server;
import org.hsqldb.persist.HsqlProperties;
import org.hsqldb.server.ServerAcl.AclFormatException;
import org.junit.Test;
public class HSQLDBInMemTest {
#Test
public void test() throws IOException, AclFormatException {
HsqlProperties props = new HsqlProperties();
props.setProperty("server.database.0", "mem:test1");
props.setProperty("server.database.1", "mem:test2");
Server hsqlServer = new Server();
hsqlServer.setRestartOnShutdown(false);
hsqlServer.setNoSystemExit(true);
hsqlServer.setProperties(props);
hsqlServer.start();
hsqlServer.shutdown();
}
}
The path for a memory database looks like props.setProperty("server.database.0", "mem:test1");

JUnit reporter does not show detailed report for each step in JBehave

I'm trying to set up JBehave for testing web services.
Template story is running well, but I can see in JUnit Panel only Acceptance suite class execution result. What I want is to see execution result for each story in suite and for each step in story like it is shown in simple JUnit tests or in Thucydides framework.
Here is my acceptance suite class: so maybe I Haven't configured something, or either I have to notate my step methods some other way, but I didn't find an answer yet.
package ***.qa_webservices_testing.jbehave;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import org.jbehave.core.Embeddable;
import org.jbehave.core.configuration.Configuration;
import org.jbehave.core.configuration.MostUsefulConfiguration;
import org.jbehave.core.io.CodeLocations;
import org.jbehave.core.io.LoadFromClasspath;
import org.jbehave.core.io.StoryFinder;
import org.jbehave.core.junit.JUnitStories;
import org.jbehave.core.parsers.RegexPrefixCapturingPatternParser;
import org.jbehave.core.reporters.CrossReference;
import org.jbehave.core.reporters.Format;
import org.jbehave.core.reporters.StoryReporterBuilder;
import org.jbehave.core.steps.InjectableStepsFactory;
import org.jbehave.core.steps.InstanceStepsFactory;
import org.jbehave.core.steps.ParameterConverters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ***.qa_webservices_testing.jbehave.steps.actions.TestAction;
/**
* suite class.
*/
public class AcceptanceTestSuite extends JUnitStories {
private static final String CTC_STORIES_PATTERN = "ctc.stories";
private static final String STORY_BASE = "src/test/resources";
private static final String DEFAULT_STORY_NAME = "stories/**/*.story";
private static final Logger LOGGER = LoggerFactory.getLogger(AcceptanceTestSuite.class);
private final CrossReference xref = new CrossReference();
public AcceptanceTestSuite() {
configuredEmbedder()
.embedderControls()
.doGenerateViewAfterStories(true)
.doIgnoreFailureInStories(false)
.doIgnoreFailureInView(true)
.doVerboseFailures(true)
.useThreads(2)
.useStoryTimeoutInSecs(60);
}
#Override
public Configuration configuration() {
Class<? extends Embeddable> embeddableClass = this.getClass();
Properties viewResources = new Properties();
viewResources.put("decorateNonHtml", "true");
viewResources.put("reports", "ftl/jbehave-reports-with-totals.ftl");
// Start from default ParameterConverters instance
ParameterConverters parameterConverters = new ParameterConverters();
return new MostUsefulConfiguration()
.useStoryLoader(new LoadFromClasspath(embeddableClass))
.useStoryReporterBuilder(new StoryReporterBuilder()
.withCodeLocation(CodeLocations.codeLocationFromClass(embeddableClass))
.withDefaultFormats()
.withViewResources(viewResources)
.withFormats(Format.CONSOLE, Format.TXT, Format.HTML_TEMPLATE, Format.XML_TEMPLATE)
.withFailureTrace(true)
.withFailureTraceCompression(false)
.withMultiThreading(false)
.withCrossReference(xref))
.useParameterConverters(parameterConverters)
// use '%' instead of '$' to identify parameters
.useStepPatternParser(new RegexPrefixCapturingPatternParser(
"%"))
.useStepMonitor(xref.getStepMonitor());
}
#Override
protected List<String> storyPaths() {
String storiesPattern = System.getProperty(CTC_STORIES_PATTERN);
if (storiesPattern == null) {
storiesPattern = DEFAULT_STORY_NAME;
} else {
storiesPattern = "**/" + storiesPattern;
}
LOGGER.info("will search stories by pattern {}", storiesPattern);
List<String> result = new StoryFinder().findPaths(STORY_BASE, Arrays.asList(storiesPattern), Arrays.asList(""));
for (String item : result) {
LOGGER.info("story to be used: {}", item);
}
return result;
}
#Override
public InjectableStepsFactory stepsFactory() {
return new InstanceStepsFactory(configuration(), new TestAction());
}
}
my test methods look like:
Customer customer = new cutomer();
#Given ("I have Access to Server")
public void givenIHaveAccesToServer() {
customer.haveAccesToServer();
}
So they are notated only by JBehave notations.
The result returned in Junit panel is only like here (I yet have no rights to post images):
You should try this open source library:
https://github.com/codecentric/jbehave-junit-runner
It does exactly what you ask for :)
Yes, the codecentric runner works very nicely.
https://github.com/codecentric/jbehave-junit-runner

Play 2 framework testing simulate session and POST?

When running a web test like this
#Test
public void runInBrowser() {
running(testServer(3333), HtmlUnitDriver.class, new Callback<TestBrowser>() {
public void invoke(TestBrowser browser) {
browser.goTo("http://localhost:3333");
assertThat(browser.$("#title").getTexts().get(0)).isEqualTo("Hello Guest");
browser.$("a").click();
assertThat(browser.url()).isEqualTo("http://localhost:3333/Coco");
assertThat(browser.$("#title", 0).getText()).isEqualTo("Hello Coco");
}
});
}
How can one pass sessions values while using this kind of testing and how can one simulate a POST? Thanks :-)
These are Selenium tests with FluentLenium. Since you test with a browser you must use an HTML form with method POST to make a POST request.
browser.goTo("http://localhost:3333" + routes.Login.login().url());//example for reverse route, alternatively use something like "http://localhost:3333/login"
browser.fill("#password").with("secret");
browser.fill("#username").with("aUsername");
browser.submit("#signin");//trigger submit button on the form
//after finished request: http://www.playframework.org/documentation/api/2.0.4/java/play/test/TestBrowser.html
browser.getCookies(); //read only cookies
Maybe you don't want to make test with a browser but instead with HTTP you can use FakeRequests:
import static controllers.routes.ref.Application;
import static org.fest.assertions.Assertions.assertThat;
import static play.mvc.Http.Status.OK;
import static play.mvc.Http.Status.UNAUTHORIZED;
import static play.test.Helpers.*;
import play.libs.WS;
import java.util.HashMap;
import java.util.Map;
import org.junit.BeforeClass;
import org.junit.Test;
import play.mvc.Result;
import play.test.FakeRequest;
public class SoTest {
#Test
public void testInServer() {
running(testServer(3333), new Runnable() {
public void run() {
Fixtures.loadAll();//you may have to fill your database you have to program this yourself
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("userName", "aUsername");
parameters.put("password", "secret");
FakeRequest fakeRequest = new FakeRequest().withSession("key", "value").withCookies(name, value, maxAge, path, domain, secure, httpOnly).withFormUrlEncodedBody(parameters);
Result result = callAction(Application.signIn(), fakeRequest);
int responseCode = status(result);
assertThat(responseCode).isEqualTo(OK);
}
});
}
}
Also check out this answer: How to manipulate Session, Request and Response for test in play2.0