Read different values from Excel file every time when test case runs - selenium

I have create a excel file with some codes and I am using RepeatRule class to execute my test case 100 times in one class. I need to use different 100 codes every time the test will run rather than using the same code again and again. Below is my code
#Test
#Repeat(2)
public void Test() throws Exception {
Success.setUp();
Success.allowcokkies();
//Success.Ecoomerecemain();
File source = new File("/Users/test/Downloads/Voucher-codes.xlsx");
FileInputStream input = new FileInputStream(source); // Read Excel Data
XSSFWorkbook wb = new XSSFWorkbook(input);
XSSFSheet sheet = wb.getSheetAt(0);
int noOfColumns = sheet.getRow(0).getLastCellNum();
System.out.println(noOfColumns);
String[] Headers = new String[noOfColumns];
int j=0;
Headers[j] = sheet.getRow(0).getCell(j).getStringCellValue();
Success.getDriver().findElement(By.xpath("//*[#id=\"code\"]")).sendKeys(sheet.getRow(0).getCell(j).getStringCellValue());// Enter Coupon
Thread.sleep(2000);
}
#After
public void testdown()
{
Success.getDriver().quit();
This is repeat class code:
public class RepeatRule implements TestRule {
public static class RepeatStatement extends Statement {
private final Statement statement;
private final int repeat;
public RepeatStatement(Statement statement, int repeat) {
this.statement = statement;
this.repeat = repeat;
}
#Override
public void evaluate() throws Throwable {
for (int i = 0; i < repeat; i++) {
statement.evaluate();
}
}
}
#Override
public Statement apply(Statement statement, Description description) {
Statement result = statement;
Repeat repeat = description.getAnnotation(Repeat.class);
if (repeat != null) {
int times = repeat.value();
result = new RepeatStatement(statement, times);
}
return result;
}
}
How can I read different codes every time while using Repeat rule?

The easy way to do this is a JUnit 5 parameterized test. Save your Excel sheet as csv and use the following test method:
#ParameterizedTest
#CsvFileSource(resources = "/Users/test/Downloads/Voucher-codes.csv", numLinesToSkip = 1)
void testVoucher(String coupon) {
...
Success.getDriver().findElement(By.xpath("//*[#id=\"code\"]")).sendKeys(coupon);// Enter Coupon
...
}
Parameterized tests are possible with JUnit 4 as well. An example is described in the JUnit Wiki. You can even use the Excel sheet as a data provider with your POI code.
Another solution would be using #BeforeEach, where you could update a coupon field couponIndex in your test class and access the right row by the value of this field.
Success.getDriver().findElement(By.xpath("//*[#id=\"code\"]")).sendKeys(sheet.getRow(couponIndex).getCell(j).getStringCellValue());// Enter Coupon
I would recommend using a parameterized test.

Related

Writing Junit by using Mockito for batch Update

Can please write the JUnit code by using Mockito for the following code :
public void writeToNoClaimLeftBehindMMF(List<NoClaimLeftMedicaidMaster> nclmm) throws Exception {
String query = Queries.NO_CLAIM_LEFT_MMF_INSERT_QUERY;
MapSqlParameterSource[] params = new MapSqlParameterSource[nclmm. Size()];
for (int i = 0; i < nclmm. Size(); i++) {
params[i] = new MapSqlParameterSource()
.addValue("envId", nclmm.get(i).getENV_ID());
mysqlJdbcTemplate.batchUpdate(query, params);
It depends on what exact behaviour of writeToNoClaimLeftBehindMMF you are trying to test. Assuming that you want to mock your mysqlJdbcTemplate instance, you will have to inject the mock as a class constructor argument and the test code would be something like this:
#Test
public void whenEmptyListIsPassed_thenWriteToNoClaimLeftBehindMMFGoesBlahBlah() {
// Given
var mockJdbcTemplate = mock(JdbcTemplate.class);
when(mockJdbcTemplate.batchUpdate(...,...)).thenReturn(whatever);
var systemUnderTest = new WhateverYourClassIsCalled(mockJdbcTemplate);
// When
systemUnderTest.writeToNoClaimLeftBehindMMF(List.of());
// Then
assertTrue(whatever you're testing);
}
See https://javadoc.io/doc/org.mockito/mockito-core/latest/index.html

Intellitest Pex Parameterize Mock

public enum SystemConstants
{
SystemTypeDocument,
ApplicationTypeDocument
}
public interface ISystemBaseObject
{
SystemConstants SystemType();
}
public class ExploreMockExample
{
ISystemBaseObject systemBaseObject;
public ExploreMockExample(ISystemBaseObject systemObject)
{
systemBaseObject = systemObject;
}
public int MethodToBeTested()
{
if (systemBaseObject.SystemType() == SystemConstants.SystemTypeDocument)
{
return 1;
}
else
{
return 2;
}
}
}
Using intellitest along with NUnit3.
When I right click MethodToBeTested, and then select run intellitest, expected outcome is Intellitest test should achieve maximum code coverage and create test case with valid test data to cover both if (systemBaseObject.SystemType() == SystemConstants.SystemTypeDocument) and else branch statement.
Some blogs suggested to create factory for class and create mock object of interface. And use PexChoose static method to allow pex framework to explore code to achieve maximum code coverage.
[PexFactoryMethod(typeof(ExploreMockExample))]
public static ExploreMockExample CreateMock()
{
var mockComosBaseObject = new Mock<ISystemBaseObject>();
mockComosBaseObject.Setup(c =>c.SystemType()).
Returns(PexChoose.EnumValue<SystemConstants>(nameof(SystemConstants)));
return new ExploreMockExample(mockComosBaseObject.Object);
}
With above setup, Intellitest could above to generate only one test case which is covering if statement, if (systemBaseObject.SystemType() == SystemConstants.SystemTypeDocument).
What can be done, to allow intellitest to create test case which will cover else statement having result value as 2.
Create mock implementation for your interface. Like mentioned below,
public class SystemBaseObject : ISystemBaseObject
{
public SystemConstants SystemType()
{
return PexChoose.EnumValue<SystemConstants>("SystemConstants");
}
}
PexChoose will help intellitest to explore code, return value will depend upon uses of SystemConstants in original class.
Then, create factory of ExploreMockExample using SystemBaseObject,
[PexFactoryMethod(typeof(ExploreMockExample))]
public static ExploreMockExample Create()
{
return new ExploreMockExample(new SystemBaseObject());
}
Run Intellitest on actual method MethodToBeTested, Intellitest will create 2 unit test case to cover both if else branch statement.
First test case,
[PexGeneratedBy(typeof(ExploreMockExampleTest))]
public void MethodToBeTested806()
{
ExploreMockExample exploreMockExample;
int i;
exploreMockExample = ExploreMockExampleFactory.Create();
i = this.MethodToBeTested(exploreMockExample);
PexAssert.AreEqual<int>(1, i);
PexAssert.IsNotNull((object)exploreMockExample);
}
Kindly observe PexAssert.AreEqual(1, i), which will cover if branch.
Second test case,
[PexGeneratedBy(typeof(ExploreMockExampleTest))]
public void MethodToBeTested792()
{
ExploreMockExample exploreMockExample;
int i;
exploreMockExample = ExploreMockExampleFactory.Create();
IPexChoiceRecorder choices = PexChoose.Replay.Setup();
choices.NextSegment(1).DefaultSession
.At(0, "SystemConstants", (object)(SystemConstants.ApplicationTypeDocument));
i = this.MethodToBeTested(exploreMockExample);
PexAssert.AreEqual<int>(2, i);
PexAssert.IsNotNull((object)exploreMockExample);
}
Kindly observe PexAssert.AreEqual(2, i), which will cover else branch.
Using PexChoose.Replay.Setup() it will return IPexChoiceRecorder, and it will make choice about to have SystemConstants.ApplicationTypeDocument as argument value to cover else block.

How to pass bean class to a test method in testng?

I have an Excel Util which reads all the data from excel sheet. The excel sheet has 10 columns like time, sourceType, tid, message, severity,
lastModify, entityName, operationType, replayId, recordIds.
My DataProvider has code something like this which returns all the 10 columns and their values.
#DataProvider(name="googleData")
public static Object[][] testData() {
String filePath = "/Users/TestUser/Workspace/FixProject/ExcelCheck/src/test/resources/excelreader.xlsx";
Object[][] arrayObject = excelFileUtils.getExcelData(filePath, "excelreader");
return arrayObject;
}
In My TestMethod, I have to pass all these 10 columns or else it wont allow me to run. Instead I want to create a Bean Class and pass something like this to my test method
#Test(dataProvider = "googleData", dataProviderClass = DataProviders.class)
public void testGoogleData(BeanClass object) {
System.out.println(object.getTid());
}
How do we achieve this?
Using the dataProvider you have, your test method is going to run 10 times for each object in the array.
What you can do is to create an object, convert your dataProvider into that object and than use it your test method code.
Object myDataHelper = null;
#Test()
public void testGoogleData(BeanClass object) {
myDataHelper = convertDataProviderToObject();
// use it here in a for/for each loop
System.out.println(object.getTid());
}
public static Object[][] read_excel(String Sheet_Name) throws Exception
{
File obj = new File("./src/main/java/com/Demo/TestData/Test_Data.xlsx");
FileInputStream fis = new FileInputStream(obj);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet = wb.getSheet(Sheet_Name);
int row_number = sheet.getLastRowNum();
int column_number = sheet.getRow(0).getLastCellNum();
Object data[][] = new Object[row_number][column_number];
wb.close();
for(int i=0; i<row_number; i++)
{
for(int j=0; j<column_number; j++)
{
data[i][j] = sheet.getRow(i + 1).getCell(j).toString();
}
}
return data;
}
#DataProvider
public Object[][] getDataFromExcel() throws Exception
{ Object[][] data = Utility.read_excel("Admin_Credentials");//Sheet name
return data;
}
#Test(dataProvider="getDataFromExcel")
It is supported in QAF-TestNG extension. You can have one or more complex object argument in your test method while using inbuilt or custom data provider. For excel your code may look like below:
#QAFDataProvider(dataFile = "resources/data/googletestdata.xls")
#Test
public void testGoogleData(BeanClass object) {
System.out.println(object.getTid());
}
For custom data provider it may look like below:
#QAFDataProvider
#Test(dataProvider = "googleData", dataProviderClass = DataProviders.class)
public void testGoogleData(BeanClass object) {
System.out.println(object.getTid());
}
You need to make sure that,properties name in your bean class must match column names (in any order). When using custom data provider you need to return Iterator for List of Map<String, Object> or Object[][] having Map, refer few example if you required to create custom data provider.

What are "watches" in IntelliJ and how to use them?

When I debug an app, in the debug tool window there is a Watches window. I have read this manual over and over, but cannot find any practicle usage of Watches.
Somehow, I think this is a cool and useful tool and I lack from not using it.
Can someone explain when should I use it and give a few samples? Ideally, the description will be bound to a concrete (imaginary) situation so that I better apply it in my work.
This section allows you to define expressions which you'd like to see how they evolve/change with every step of your debug process, without manually inspecting all the available objects and their properties. Let's take the following simple sample which intentionally throws a NullPointerException (NPE):
public class WatchSample {
static class Student {
public static final int CREDITS_REQUIRED_FOR_GRADUATION = 10;
private String name;
private Integer credits;
public Student(String name, Integer credits) {
this.name = name;
this.credits = credits;
}
String getName() {
return name;
}
public boolean hasGraduated() {
return credits >= CREDITS_REQUIRED_FOR_GRADUATION;
}
public Integer getCredits() {
return credits;
}
}
public static void main(String[] args) throws Exception {
List<Student> students = simulateReadingFromDB();
for (Student student : students) {
if (student.hasGraduated()) {
System.out.println("Student [" + student.getName() + "] has graduated with [" + student.getCredits() + "] credits");
}
}
}
private static List<Student> simulateReadingFromDB() {
List<Student> students = new ArrayList<>(3);
students.add(new Student("S1", 15));
students.add(new Student("S2", null)); // <- simulate some mistake
students.add(new Student("S3", 10));
return students;
}
}
At some point in time you may wonder how come you get a NPE and what needs fixing. So just set a breakpoint, add a few watches and carefully step through the lines. Eventually you'll end up with the troublemaker in sight:
Of course this is a basic example and should be taken as such. Within a regular app you'll probably have more complex scenarios and expressions you'd like to inspect, and this will make more sense, for example: if (((position > 0 && position < MAX) || (position < 0 && position > MIN) && (players(currentPlayer).isNotDead() && move.isAllowed()) && time.notUp())..... In this case you can evaluate the sub-expressions to see which one returns false
**Note**: You could also make the breakpoint conditional so that the program will pause only when that specific event occurs:

Text extraction from table cells

I have a pdf. The pdf contains a table. The table contains many cells (>100). I know the exact position (x,y) and dimension (w,h) of every cell of the table.
I need to extract text from cells using itextsharp. Using PdfReaderContentParser + FilteredTextRenderListener (using a code like this http://itextpdf.com/examples/iia.php?id=279 ) I can extract text but I need to run the whole procedure for each cell. My pdf have many cells and the program needs too much time to run. Is there a way to extract text from a list of "rectangle"? I need to know the text of each rectangle. I'm looking for something like PDFTextStripperByArea by PdfBox (you can define as many regions as you need and the get text using .getTextForRegion("region-name") ).
This option is not immediately included in the iTextSharp distribution but it is easy to realize. In the following I use the iText (Java) class, interface, and method names because I am more at home with Java. They should easily be translatable into iTextSharp (C#) names.
If you use the LocationTextExtractionStrategy, you can can use its a posteriori TextChunkFilter mechanism instead of the a priori FilteredRenderListener mechanism used in the sample you linked to. This mechanism has been introduced in version 5.3.3.
For this you first parse the whole page content using the LocationTextExtractionStrategy without any FilteredRenderListener filtering applied. This makes the strategy object collect TextChunk objects for all PDF text objects on the page containing the associated base line segment.
Then you call the strategy's getResultantText overload with a TextChunkFilter argument (instead of the regular no-argument overload):
public String getResultantText(TextChunkFilter chunkFilter)
You call it with a different TextChunkFilter instance for each table cell. You have to implement this filter interface which is not too difficult as it only defines one method:
public static interface TextChunkFilter
{
/**
* #param textChunk the chunk to check
* #return true if the chunk should be allowed
*/
public boolean accept(TextChunk textChunk);
}
So the accept method of the filter for a given cell must test whether the text chunk in question is inside your cell.
(Instead of separate instances for each cell you can of course also create one instance whose parameters, i.e. cell coordinates, can be changed between getResultantText calls.)
PS: As mentioned by the OP, this TextChunkFilter has not yet been ported to iTextSharp. It should not be hard to do so, though, only one small interface and one method to add to the strategy.
PPS: In a comment sschuberth asked
Do you then still call PdfTextExtractor.getTextFromPage() when using getResultantText(), or does it somehow replace that call? If so, how to you then specify the page to extract to?
Actually PdfTextExtractor.getTextFromPage() internally already uses the no-argument getResultantText() overload:
public static String getTextFromPage(PdfReader reader, int pageNumber, TextExtractionStrategy strategy, Map<String, ContentOperator> additionalContentOperators) throws IOException
{
PdfReaderContentParser parser = new PdfReaderContentParser(reader);
return parser.processContent(pageNumber, strategy, additionalContentOperators).getResultantText();
}
To make use of a TextChunkFilter you could simply build a similar convenience method, e.g.
public static String getTextFromPage(PdfReader reader, int pageNumber, LocationTextExtractionStrategy strategy, Map<String, ContentOperator> additionalContentOperators, TextChunkFilter chunkFilter) throws IOException
{
PdfReaderContentParser parser = new PdfReaderContentParser(reader);
return parser.processContent(pageNumber, strategy, additionalContentOperators).getResultantText(chunkFilter);
}
In the context at hand, though, in which we want to parse the page content only once and apply multiple filters, one for each cell, we might generalize this to:
public static List<String> getTextFromPage(PdfReader reader, int pageNumber, LocationTextExtractionStrategy strategy, Map<String, ContentOperator> additionalContentOperators, Iterable<TextChunkFilter> chunkFilters) throws IOException
{
PdfReaderContentParser parser = new PdfReaderContentParser(reader);
parser.processContent(pageNumber, strategy, additionalContentOperators)
List<String> result = new ArrayList<>();
for (TextChunkFilter chunkFilter : chunkFilters)
{
result.add(strategy).getResultantText(chunkFilter);
}
return result;
}
(You can make this look fancier by using Java 8 collection streaming instead of the old'fashioned for loop.)
Here's my take on how to extract text from a table-like structure in a PDF using itextsharp. It returns a collection of rows and each row contains a collection of interpreted columns. This may work for you on the premise that there is a gap between one column and the next which is greater than the average width of a single character. I also added an option to check for wrapped text within a virtual column. Your mileage may vary.
using (PdfReader pdfReader = new PdfReader(stream))
{
for (int page = 1; page <= pdfReader.NumberOfPages; page++)
{
TableExtractionStrategy tableExtractionStrategy = new TableExtractionStrategy();
string pageText = PdfTextExtractor.GetTextFromPage(pdfReader, page, tableExtractionStrategy);
var table = tableExtractionStrategy.GetTable();
}
}
public class TableExtractionStrategy : LocationTextExtractionStrategy
{
public float NextCharacterThreshold { get; set; } = 1;
public int NextLineLookAheadDepth { get; set; } = 500;
public bool AccomodateWordWrapping { get; set; } = true;
private List<TableTextChunk> Chunks { get; set; } = new List<TableTextChunk>();
public override void RenderText(TextRenderInfo renderInfo)
{
base.RenderText(renderInfo);
string text = renderInfo.GetText();
Vector bottomLeft = renderInfo.GetDescentLine().GetStartPoint();
Vector topRight = renderInfo.GetAscentLine().GetEndPoint();
Rectangle rectangle = new Rectangle(bottomLeft[Vector.I1], bottomLeft[Vector.I2], topRight[Vector.I1], topRight[Vector.I2]);
Chunks.Add(new TableTextChunk(rectangle, text));
}
public List<List<string>> GetTable()
{
List<List<string>> lines = new List<List<string>>();
List<string> currentLine = new List<string>();
float? previousBottom = null;
float? previousRight = null;
StringBuilder currentString = new StringBuilder();
// iterate through all chunks and evaluate
for (int i = 0; i < Chunks.Count; i++)
{
TableTextChunk chunk = Chunks[i];
// determine if we are processing the same row based on defined space between subsequent chunks
if (previousBottom.HasValue && previousBottom == chunk.Rectangle.Bottom)
{
if (chunk.Rectangle.Left - previousRight > 1)
{
currentLine.Add(currentString.ToString());
currentString.Clear();
}
currentString.Append(chunk.Text);
previousRight = chunk.Rectangle.Right;
}
else
{
// if we are processing a new line let's check to see if this could be word wrapping behavior
bool isNewLine = true;
if (AccomodateWordWrapping)
{
int readAheadDepth = Math.Min(i + NextLineLookAheadDepth, Chunks.Count);
if (previousBottom.HasValue)
for (int j = i; j < readAheadDepth; j++)
{
if (previousBottom == Chunks[j].Rectangle.Bottom)
{
isNewLine = false;
break;
}
}
}
// if the text was not word wrapped let's treat this as a new table row
if (isNewLine)
{
if (currentString.Length > 0)
currentLine.Add(currentString.ToString());
currentString.Clear();
previousBottom = chunk.Rectangle.Bottom;
previousRight = chunk.Rectangle.Right;
currentString.Append(chunk.Text);
if (currentLine.Count > 0)
lines.Add(currentLine);
currentLine = new List<string>();
}
else
{
if (chunk.Rectangle.Left - previousRight > 1)
{
currentLine.Add(currentString.ToString());
currentString.Clear();
}
currentString.Append(chunk.Text);
previousRight = chunk.Rectangle.Right;
}
}
}
return lines;
}
private struct TableTextChunk
{
public Rectangle Rectangle;
public string Text;
public TableTextChunk(Rectangle rect, string text)
{
Rectangle = rect;
Text = text;
}
public override string ToString()
{
return Text + " (" + Rectangle.Left + ", " + Rectangle.Bottom + ")";
}
}
}