I am getting error in testng report:
I followed the below steps
I wrote all my testcases in java methods and used java verifications like if else to pass my testcases
2.I created one testng class, in the testng class i called my all java methods
I executed the testng class this class contain around 30 java methods, each and every method is one testcase.
If i execute that class reports generated for testng based annotations, it does not consider the java methods into testcases, how can i call my all java methods? i need to generate reports for my java methods
Here is my code :
import java.io.FileNotFoundException;
import java.io.IOException;
import jxl.read.biff.BiffException;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class DocumentSearchTest {
WebElements webEleObj;
/*
* AllLetter Lettobj ; AllSearch allseObj; AllTranscript TraObj;
*/
FrameSearchExported fseObj;
TextBoxSearch textObj;
DateSinceSearch dateSinceObj;
/*
* public void loginTest() throws FileNotFoundException, BiffException,
* IOException, InterruptedException {
* webEleObj.textbox(webEleObj.properties
* ("Username"),webEleObj.excelRead(1,2,1));
* webEleObj.textbox(webEleObj.properties
* ("Password"),webEleObj.excelRead(2,2,1)); webEleObj.sleep(5000);
* webEleObj.button(webEleObj.properties("Login")); webEleObj.sleep(20000);
*
* }
*/
#BeforeClass
public void start() throws FileNotFoundException, BiffException,
IOException, InterruptedException, RowsExceededException,
WriteException {
// Assert.assertEquals(true, true, "Loggend into application");
webEleObj = new WebElements();
/*
* allseObj = new AllSearch(webEleObj); Lettobj = new
* AllLetter(webEleObj); TraObj =new AllTranscript(webEleObj);
*/
fseObj = new FrameSearchExported(webEleObj);
textObj = new TextBoxSearch(webEleObj);
dateSinceObj = new DateSinceSearch(webEleObj);
webEleObj.browserLaunch();
webEleObj.loginTest();
webEleObj.sleep(20000);
webEleObj.setUpApp();
// webEleObj.excelwrite(4);
System.out.println("hi logged in");
}
#Test
public void ts_1() throws FileNotFoundException, IOException,
InterruptedException, RowsExceededException, BiffException,
WriteException {
webEleObj.sleep(10000);
System.out.println("First TestCase---->");
fseObj.allexportedSearch();
fseObj.letterexportedSearch();
fseObj.transcriptexportedSearch();
fseObj.allnotexpSearch();
fseObj.letternotexpSearch();
fseObj.transcriptnotexpSearch();
fseObj.allsignsearch();
fseObj.lettersignSearch();
fseObj.transcriptsignSearch();
fseObj.allnotsignSearch();
fseObj.letternotsignSearch();
fseObj.transcriptnotsignSearch();
System.out.println("Document Search Test Case Completed");
}
/*
* #Test(enabled=false) public void ts_2() throws FileNotFoundException,
* BiffException, IOException, InterruptedException, RowsExceededException,
* WriteException { System.out.println("Second TestCase---->");
* textObj.accountNo_All(); textObj.accountNo_Letter();
* textObj.accountNo_Transcript(); textObj.firstName_All();
* textObj.firstName_Letter(); textObj.firstName_Transcript();
* textObj.lastName_All(); textObj.lastName_Letter();
* textObj.lastName_Transcript();
*
* }
*/
#Test
public void ts_3() throws FileNotFoundException, IOException,
InterruptedException, RowsExceededException, BiffException,
WriteException {
// webEleObj.sleep(10000);
System.out.println("Third TestCase---->");
dateSinceObj.datesinceAll_Today();
dateSinceObj.datesinceAll_Yesterday();
dateSinceObj.datesinceAll_ThisMonth();
dateSinceObj.datesinceAll_LastMonth();
dateSinceObj.datesinceAll_ThisYear();
dateSinceObj.datesinceAll_LastYear();
dateSinceObj.datesinceLetter_Today();
dateSinceObj.datesinceLetter_Yesterday();
dateSinceObj.datesinceLetter_ThisMonth();
dateSinceObj.datesinceLetter_LastMonth();
dateSinceObj.datesinceLetter_ThisYear();
dateSinceObj.datesinceLetter_LastYear();
dateSinceObj.datesinceTranscript_Today();
dateSinceObj.datesinceTranscript_Yesterday();
dateSinceObj.datesinceTranscript_ThisMonth();
dateSinceObj.datesinceTranscript_LastMonth();
dateSinceObj.datesinceTranscript_ThisYear();
dateSinceObj.datesinceTranscript_LastYear();
// logOut();
}
}
You could use a jUnit testSuite where you can define all the test classes you want to run at the same time:
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
#RunWith(Suite.class)
#SuiteClasses({ MyClassTest.class, MySecondClassTest.class })
public class AllTests {
}
You can find more info # Vogella http://www.vogella.com/articles/JUnit/article.html#juniteclipse_testsuite
Here is your code for calling any java methods in testing class:--
Class A
public class A {
static void method1()
{
System.out.println("Selenium_1");
}
static void method2()
{
System.out.println("Selenium_1");
}
}
Class B
public class B extends A {
public static void main(String ar[])
{
method1();
method2();
}
}
Related
JUnit5 does not support PowerMockRunner hence the following code will not work whenever you migrate from JUnit4 to JUnit5.
Eg.
Code you trying to inject mock
import javax.naming.InvalidNameException;
public class Main {
public static void main(String[] args) {
Main main = new Main();
main.publish();
}
public void publish() {
try {
Sample s = new Sample();
s.invoke("Hello");
} catch (InvalidNameException e) {
throw new ServiceFailureException(e.getMessage());
}
}
}
Here you are trying to test publish method where you mock the Sample instance to respond with different responses.
In JUnit4 you could have use PowerMockito to achieve that.
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import javax.naming.InvalidNameException;
#RunWith(PowerMockRunner.class)
#PrepareForTest({Main.class})
public class MainTest {
#Test
public void testPublishSuccess() {
Main m = new Main();
Assert.assertEquals("Expected result not found", "success", m.publish());
}
#Test
public void testPublishFailure() throws Exception{
Sample sample = new Sample();
PowerMockito.when(sample.invoke(Mockito.anyString())).thenReturn("failure");
PowerMockito.whenNew(Sample.class).withNoArguments().thenReturn(sample);
Main m = new Main();
Assert.assertEquals("Expected result not found", "failure", m.publish());
}
#Test(expected = ServiceFailureException.class)
public void testPublishException() throws Exception{
Sample sample = new Sample();
PowerMockito.when(sample.invoke(Mockito.anyString())).thenThrow(new InvalidNameException("Invalid name provided"));
PowerMockito.whenNew(Sample.class).withNoArguments().thenReturn(sample);
Main m = new Main();
m.publish();
}
}
With the introduction of JUnit5, the test cases are failing at mock creating new instances because PowerMockRunner does not support JUnit5.
What is the alternate for using PowerMockito with JUnit5.
As PowerMockito does not support JUnit5, we can use Mockito inline. Here is the code which replace the PowerMockito.
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.MockedConstruction;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import javax.naming.InvalidNameException;
public class MainTestJunit5 {
#Test
public void testPublishSuccess() {
Main m = new Main();
Assertions.assertEquals("success", m.publish(), "Expected result not found");
}
#Test
public void testPublishFailure() throws Exception{
try (MockedConstruction<Sample> mockedConstruction = Mockito.mockConstruction(Sample.class, (sampleMock, context) -> {
Mockito.when(sampleMock.invoke(Mockito.anyString())).thenReturn("failure");
})) {
Sample sample = new Sample();
PowerMockito.when(sample.invoke(Mockito.anyString())).thenReturn("failure");
PowerMockito.whenNew(Sample.class).withNoArguments().thenReturn(sample);
Main m = new Main();
Assertions.assertEquals("Expected result not found", "failure", m.publish());
}
}
#Test
public void testPublishException() throws Exception{
try (MockedConstruction<Sample> mockedConstruction = Mockito.mockConstruction(Sample.class, (sampleMock, context) -> {
Mockito.when(sampleMock.invoke(Mockito.anyString())).thenThrow(new InvalidNameException("Invalid name found"));
})){
Main m = new Main();
boolean error = false;
try {
m.publish();
} catch (ServiceFailureException e) {
error = true;
}
Assertions.assertTrue(error, "Exception throwing expected");
}
}
}
Couple of things you need to pay attention
Setting up mockito-inline need additional dependency and an additional configuration.
Extra test runners (PowerMockRunner) and preparation for testing is not needed.
MockedConstruction is scoped, so you have to put all the mocking and processing done within that code block.
JUnit5 messages are the final method argument.
Mockito documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#49
I'm trying to use my input from the console to pick which class's main method I want to run.
package run;
import java.lang.reflect.Method;
import java.util.Scanner;
import testing.*;
public class run {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException{
Scanner input = new Scanner(System.in);
String name = "testing."+input.nextLine();
Class Program = Class.forName(name);
//Try 1
Program obj = new Program();
//Got error "Program cannot be resolved to a type" on program and program
//Try 2
Program.main();
//Got error "The method main() is undefined for the type Class" on main
//Try 3
Class.forName(name).main();
//Got error "The method main() is undefined for the type Class<capture#2-of ?>" on main
}
}
Class program = Class.forName(name);
program.getDeclaredMethod("main", String[].class).invoke(null, new Object[]{args});
provide your main method is public static void main(String[] args)
This problem can be solved easily using Reflection. Check out the code below:
package run;
import java.lang.reflect.Method;
import java.util.Scanner;
import testing.*;
public class run {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, NegativeArraySizeException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Scanner input = new Scanner(System.in);
String name = "testing."+input.nextLine();
Class program = Class.forName(name);
program.getMethod("main", String[].class).invoke(null, Array.newInstance(String.class, 0));
}
}
While LeanFT uses JUnit for its test runner, it doesn't appear to implement 'TestRule'. This excludes a 'standard' method describe elsewhere.
How to Re-run failed JUnit tests immediately?
Anyone have a solution to this?
It seems that you refer to the fact that the report doesn't have the test result.
Indeed it seems it's no longer automatically reported when using TestRule.
However, you can manually report whatever you want to report.
Here's an example of Junit test that reports what we want it to report.
import com.hp.lft.report.CaptureLevel;
import com.hp.lft.report.ReportLevel;
import com.hp.lft.report.Reporter;
import com.hp.lft.sdk.web.Browser;
import com.hp.lft.sdk.web.BrowserFactory;
import com.hp.lft.sdk.web.BrowserType;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.*;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import unittesting.UnitTestClassBase;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
public class RetryTest extends UnitTestClassBase {
#BeforeClass
public static void setUpBeforeClass() throws Exception {
instance = new LeanFtTest();
globalSetup(LeanFtTest.class);
}
#AfterClass
public static void tearDownAfterClass() throws Exception {
globalTearDown();
}
public class Retry implements TestRule {
private int retryCount;
public Retry(int retryCount) {
this.retryCount = retryCount;
}
public Statement apply(Statement base, Description description) {
return statement(base, description);
}
private Statement statement(final Statement base, final Description description) {
return new Statement() {
#Override
public void evaluate() throws Throwable {
Throwable caughtThrowable = null;
// implement retry logic here
for (int i = 0; i < retryCount; i++) {
try {
base.evaluate();
return;
} catch (Throwable t) {
caughtThrowable = t;
System.err.println(description.getDisplayName() + ": run " + (i+1) + " failed");
}
}
System.err.println(description.getDisplayName() + ": giving up after " + retryCount + " failures");
throw caughtThrowable;
}
};
}
}
#Rule
public Retry retry = new Retry(3);
#Test
public void test2() throws Exception{
Reporter.startReportingContext("Reporting for test2");
Reporter.reportEvent("Reporting", "Reporting stuff", Status.Passed);
Reporter.reportEvent("Reporting", "Reporting some more stuff", Status.Failed);
Reporter.endReportingContext();
Object o = null;
o.equals("foo");
}
}
And this is how it looks like:
Lets say I'm working in a very large project, and have noticed an empty print line, so I'm assuming there is a System.out.println(""); located somewhere in the code. How would I go about trying to figure out where it is, short of just searching the entire project for all occurrences of System.out.println?
If you're using Java 8+, Durian has a StackDumper class which makes it easy to find where a given line is being printed:
StackDumper.dumpWhenSysOutContains("SomeTrigger")
When "SomeTrigger" is printed, this will get dumped to System.err:
+----------\
| Triggered by SomeTrigger
| at package.MyClass.myMethod(MyClass.java:62)
| (the rest of the stacktrace)
+----------/
For your case (looking for an empty string), it's a little more complicated:
PrintStream sysOutClean = System.out;
StringPrinter sysOutReplacement = new StringPrinter(StringPrinter.stringsToLines(line -> {
if (line.isEmpty()) {
StackDumper.dump("Found empty line");
}
sysOutClean.println(line);
}));
System.setOut(sysOutReplacement.toPrintStream());
Now if there's something like this:
System.out.println("ABC");
System.out.println("123");
System.out.println("");
System.out.println("DEF");
Then your console will look like this:
ABC
123
+----------\
| Found empty line
| at package.MyClass.myMethod(MyClass.java:62)
| (the rest of the stacktrace)
+----------/
DEF
You could implement your own PrintStream and use System.setOut to replace the default stdout. Then either put a debugging marker inside the class (if an empty string is printed), or print out the method name through the call stack (throw and catch an exception and get the stack information).
Example:
/** Control sysout prints */
public static void main(String[] arg) throws Exception {
System.out.println("Default"); //print normally
SysOutController.setSysOutLocationAddressor();
System.out.println("With Address"); //prints with calling location, and on click location cursor directly focus when System.out.**() called
SysOutController.ignoreSysout();
System.out.println("Ignored"); //this line will never prints
SysOutController.resetSysOut();
System.out.println("Default"); //print normally as it is (reset)
}
Just call methods of following class, which helps developers to controll sysout
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
/**
* Class which controls System.out prints in console <br/>
* this class will helps developers to control prints in console
* #implSpec
* <pre><code>
* System.out.println("Default"); //print normally
*
* SysOutController.setSysOutLocationAddressor();
* System.out.println("With Address"); //prints with calling location
*
* SysOutController.ignoreSysout();
* System.out.println("Ignored"); //this line will never prints
*
* SysOutController.resetSysOut();
* System.out.println("Default"); //print normally as it is (reset)
* </code></pre>
* #author Dharmendrasinh Chudasama
*/
public class SysOutController {
private static void setOut(OutputStream out){
System.setOut(new PrintStream(out));
}
private static final OutputStream CONSOLE = new FileOutputStream(FileDescriptor.out);
/**
* Reset System.out.print* method
* #author Dharmendrasinh Chudasama
*/
public static void resetSysOut() { setOut(CONSOLE); }
/**
* System.out.print* will not print anything in console
* #author Dharmendrasinh Chudasama
*/
public static void ignoreSysout() {
setOut(new OutputStream() {
#Override public void write(int b) throws IOException {}
});
}
/**
* Address/location of calling System.out.* method will append in console
* #author Dharmendrasinh Chudasama
*/
public static void setSysOutLocationAddressor() {
setOut(new OutputStream() {
#Override
public void write(int b) throws IOException {
if(b=='\n'){ //if newLine
final StackTraceElement callerStEl = new Throwable().getStackTrace()[9];
String pathData =
"\u001B[37m" //low-visibality
+ "\t :: ("+callerStEl.getFileName()+":"+callerStEl.getLineNumber()+") ["+callerStEl+"]" //code path
+ "\u001B[0m "; //reset
CONSOLE.write(pathData.getBytes());
}
CONSOLE.write(b);
}
});
}
}
This can be due to some of the library also,if you feel that it is because of only System.out.println then,
Solution 1 :
Below code snippet should help you to find out the place where it is getting executed.
import java.io.FileNotFoundException;
import java.io.PrintStream;
public class CustomPrintStream extends PrintStream {
public CustomPrintStream(String fileName) throws FileNotFoundException {
super(fileName);
}
#Override
public void print(String s) {
try{
if(s == null || s.equals("")){
throw new Exception("Invalid print message");
}
super.print(s);
}catch(Exception e){
//TODO Change to your logger framework and leave it as same
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
//TODO : Change to your favorite path and make sure mentioned
//file is available
CustomPrintStream customPrintStream = new CustomPrintStream
("/home/prem/Desktop/test.log");
System.setOut(customPrintStream);
System.out.println("");
} catch (FileNotFoundException e) {
//TODO Change to your logger framework and leave it as same
e.printStackTrace();
}
}
}
Solution 2 :
Since IDE's are available,please get the help from them.If you are using eclipse
Menu -> Search - > File Search-> Place System.out.println(""); in containing search and search for it.
I would rather say not to use the System.out.println in any of the code,for which you can make use of checkstyle and be confident that hence forth no developers use them.
Define a class NewPrintStream extends PrintStream
import java.io.FileNotFoundException;
import java.io.PrintStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class NewPrintStream extends PrintStream {
private static final Logger LOGGER = LoggerFactory.getLogger(NewPrintStream.class);
public NewPrintStream(String fileName) throws FileNotFoundException {
super(fileName);
}
#Override
public void println(String x) {
LOGGER.info("xxxxxxx", new Exception("xxxx"));
}
}
Then in main class set stdout/stderr print stream
System.setOut(new NewPrintStream("aaa"));
System.setErr(new NewPrintStream("aaa"));
Put a conditional breakpoint in PrintStream.println(String x) with the condition set to x.equals("") or whatever your string may be.
I am trying to run the below code in Eclipse.
It's giving me an error "Editor does not contain a main type" but it does as you can see public static void main(String args[]).
Anyone know how to run this or why it does not recognize the main method?
package org.axiondb.functional;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* #version $Revision: 1.26 $ $Date: 2005/05/03 18:02:23 $
* #author Rodney Waldhoff
* #author Chuck Burdick
*/
public class TestAll extends TestCase {
public TestAll(String testName) {
super(testName);
}
public static void main(String args[]) {
String[] testCaseName = { TestAll.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
public static Test suite() {
TestSuite suite = new TestSuite();
suite.addTest(TestDatatypes.suite());
suite.addTest(TestDDL.suite());
suite.addTest(TestDQL.suite());
suite.addTest(TestDQLMisc.suite());
suite.addTest(TestDQLDisk.suite());
suite.addTest(TestDQLWithArrayIndex.suite());
suite.addTest(TestDQLDiskWithArrayIndex.suite());
suite.addTest(TestDQLWithBTreeIndex.suite());
suite.addTest(TestDQLDiskWithBTreeIndex.suite());
suite.addTest(TestDML.suite());
suite.addTest(TestDMLMisc.suite());
suite.addTest(TestDMLDisk.suite());
suite.addTest(TestDMLWithArrayIndex.suite());
suite.addTest(TestDMLDiskWithArrayIndex.suite());
suite.addTest(TestDMLWithBTreeIndex.suite());
suite.addTest(TestDMLDiskWithBTreeIndex.suite());
suite.addTest(TestMemoryClob.suite());
suite.addTest(TestDiskClob.suite());
suite.addTest(TestMemoryBlob.suite());
suite.addTest(TestDiskBlob.suite());
suite.addTest(TestThreadedSelect.suite());
suite.addTest(TestIndexedJoin.suite());
suite.addTest(TestBugs.suite());
suite.addTest(TestAxionBTreeDelete.suite());
suite.addTest(TestSpecials.suite());
suite.addTest(TestFunctions.suite());
suite.addTest(TestThreadedDML.suite());
suite.addTest(TestTransactions.suite());
suite.addTest(TestTransactionsDisk.suite());
suite.addTest(TestConstraints.suite());
suite.addTest(TestBooleanLiterals.suite());
suite.addTest(TestTransactionalLobs.suite());
suite.addTest(TestTransactionalLobsDisk.suite());
suite.addTest(TestMetaData.suite());
suite.addTest(TestMetaDataDisk.suite());
suite.addTest(TestDatabaseLock.suite());
suite.addTest(TestIndexSpecials.suite());
suite.addTest(TestForElmar.suite());
suite.addTest(TestPrepareStatement.suite());
suite.addTest(TestGroupByAndOrderBy.suite());
suite.addTest(TestBinaryStream.suite());
return suite;
}
}
Try reopening the file, then run the test.
Otherwise, restart Eclipse. please let me know if this solves the problem! or else give me more details and I'll try and help.