Printing JUnit result to file - java

I want to print the results of my JUnit tests to a .txt file.
Following is my code:
try {
//Creates html header
String breaks = "<html><center><p><h2>"+"Test Started on: "+df.format(date)+"</h2></p></center>";
//Creating two files for passing and failing a test
File pass = new File("Result_Passed-"+df.format(date)+ ".HTML");
File failed = new File("Result_Failed-"+df.format(date)+ ".HTML");
OutputStream fstreamF = new FileOutputStream(failed, true);
OutputStream fstream = new FileOutputStream(pass, true);
PrintStream p = new PrintStream(fstream);
PrintStream f= new PrintStream(fstreamF);
//appending the html code to the two files
p.append(breaks);
f.append(breaks);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Following is my example testcase:
public void test_001_AccountWorld1() {
// Open the MS CRM form to be tested.
driver.get(crmServerUrl + "account");
nameOfIFRAME = "IFRAME_CapCRM";
PerformCRM_World1("address1_name", "address1_name", "address1_line1", "address1_postalcode", true);
assertEquals(firstLineFromForm.toString(), "");
assertEquals(secondLineFromForm.toString(), "Donaustadtstrasse Bürohaus 1/2 . St");
assertEquals(postcodeFromForm.toString(), "1220");
}
I've tried p.append() but doesn't work. Help please.

In general , you can redirect your output to file as follows :
- if you are using eclipse :
Run configuration-->Commons-->OutputFile-->Your file name
If you run form the command line , just use :
java ..... >output.txt

You're probably re-inventing the wheel here. ANT, Maven, X build tool or your CI server should be doing this for you.

When I am looking to do this, I run it command line, with a custom runner, running a custom suite. Very simple, almost no code. The suite just has the test you want to run, and the runner is below.. You can see the logic there for printing out. My code just prints out errors, but you can adapt this easily to print everything to file. Essentially you are just looking in the result object collection of failures and successes.
public class UnitTestRunner {
static JUnitCore junitCore;
static Class<?> testClasses;
public static void main(String[] args) {
System.out.println("Running Junit Test Suite.");
Result result = JUnitCore.runClasses(TestSuite.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println("Successful: " + result.wasSuccessful() +
" ran " + result.getRunCount() +" tests");
}
}

I believe this functionality already exists. Read this part of JUnit's FAQ.

Related

Problem in running Test Fragment using JMeter JMX script using Java code

I have JMeter script having many test elements like test fragments, include controllers , beanshell samplers, ssh samplers, SFTP samplers, JDBC etc. When I tried running JMX script using Java code( below) some of the test elements are getting skipped.One of the major problem is it is skipping Test fragments with out going inside another JMX script.We are running Test Fragments using include controllers which we tried all the combinations of paths.Please help to run test fragments inside JMX file using below Java code.
I tried all the paths inside JMX scripts, I added all JMeter Jars in maven repository etc.
public class Test_SM_RS_001_XML extends BaseClass {
public void Test121() throws Exception {
StandardJMeterEngine jmeter = new StandardJMeterEngine();
Summariser summer = null;
JMeterResultCollector results;
File JmxFile1 = new File(/path/to/JMX/File/test121.jmx");
HashTree testPlanTree = SaveService.loadTree(JmxFile1);
testPlanTree.getTree(JmxFile1);
jmeter.configure(testPlanTree);
String summariserName = JMeterUtils.getPropDefault("summariser.name", "TestSummary");
if (summariserName.length() > 0) {
summer = new Summariser(summariserName);
}
results = new JMeterResultCollector(summer);
testPlanTree.add(testPlanTree.getArray()[0], results);
jmeter.runTest();
while (jmeter.isActive())
{
System.out.println("StandardJMeterEngine is Active...");
Thread.sleep(3000);
}
if (results.isFailure())
{
TestAutomationLogger.error("TEST FAILED");
Assert.fail("Response Code: " + JMeterResultCollector.getResponseCode() + "\n" + "Response Message: " + JMeterResultCollector.getResponseMessage() + "\n" + "Response Data: " + JMeterResultCollector.getResponseData());
}
}
}
I expect to run Test fragments inside JMX file ,but it is not considering and Skipping.
Your test code is lacking essential bit: resolving of Module and Include controllers which need to be traversed and added to the "main" HashTree
So you need to replace this line:
testPlanTree.getTree(JmxFile1);
with these:
JMeterTreeModel treeModel = new JMeterTreeModel(new Object());
JMeterTreeNode root = (JMeterTreeNode) treeModel.getRoot();
treeModel.addSubTree(testPlanTree, root);
SearchByClass<ReplaceableController> replaceableControllers =
new SearchByClass<>(ReplaceableController.class);
testPlanTree.traverse(replaceableControllers);
Collection<ReplaceableController> replaceableControllersRes = replaceableControllers.getSearchResults();
for (ReplaceableController replaceableController : replaceableControllersRes) {
replaceableController.resolveReplacementSubTree(root);
}
HashTree clonedTree = JMeter.convertSubTree(testPlanTree, true);
and this one:
jmeter.configure(testPlanTree);
with this one:
jmeter.configure(clonedTree);
More information: Five Ways To Launch a JMeter Test without Using the JMeter GUI

Java Junit failing when expected and actual are the same?

I have finished developing a big project I have been working on. I have usually done my own tests without Junit but my requirement is to use it now. All of my methods that I want to test are void and do not return anything, but print information depending on certain factors. So, I need to test these using the assertEquals method for Junit.
For example:
public void addContact(String firstName,String lastName,Person p) {
String key = firstName.substring(0,1).toUpperCase() + firstName.substring(1).toLowerCase() + " ".concat(lastName.substring(0,1).toUpperCase() + lastName.substring(1).toLowerCase());
if(hasContact(key)){
System.out.println("\nCannot add user. User already exists. Try adding distinct name to diffentiate between users with the same name");
}
else{
this.contacts.put(key,p);
System.out.println("\nUser: " + key + " Successfully added");
}
}
This is one of the void methods I want to test from my AddressBook class, for now, I am testing to see if the user can be added so it should print \nUser: " + key + " Successfully added which it does.
Here in my JUNIT test class, I am trying to check this like so...
#Test
public void addContact(){
final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
Address a1 = new Address("grove","Waterford","Waterford","x9123r","0987654321");
Person p1 = new Person("Charlie","Ansell",a1);
System.setOut(new PrintStream(outContent));
ad1.addContact("Charlie","Ansell", p1);
assertEquals("User: Charlie Ansell Successfully added", outContent.toString());
}
The output from Junit is: expected:<[User: Charlie Ansell Successfully added]> but was <[User: Charlie Ansell Successfully added]>
My question is, why is this failing if they are showing the same output?
have you tried debugging it and looking at the difference?
My guess - missing \n both at the beginning (from your code) and the end (you are using println).
this should work:
assertEquals("\nUser: Charlie Ansell Successfully added\n", outContent.toString());
Despite content looks similar you have extra line breaks (\n) in your program that your did not include in your test.
Replace:
assertEquals("User: Charlie Ansell Successfully added", outContent.toString());
with:
assertEquals("\nUser: Charlie Ansell Successfully added\n", outContent.toString());
Okay, so I have just discovered the answer.
I added the .trim() function at the end of the expected object and actual object. so my new code looks like this:
#Test
public void addContact(){
final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
Address a1 = new Address("grove","Waterford","Waterford","x9123r","0987654321");
Person p1 = new Person("Charlie","Ansell",a1);
System.setOut(new PrintStream(outContent));
ad1.addContact("Charlie","Ansell", p1);
assertEquals("\nUser: Charlie Ansell Successfully added\n".trim(), outContent.toString().trim());
}
My assumption from this is that there were blank spaces in both of the outputs, thanks to all who commented, I appreciate the help

JUnit test for tess4J application

I want to test my method to see if it will read the file correctly. I just can't seem to wrap my head around JUnit Testing. Can someone show me how to correctly write a JUnit test for this code:
import java.io.File;
import net.sourceforge.tess4j.*;
import net.sourceforge.tess4j.util.LoadLibs;
public class ImageTest {
public static String imageService(String filePath) {
File imageFile = new File("tessImage.png");
ITesseract instance = new Tesseract();
//Let tessdata be extracted in case you dont have tessdata folder
File tessDataFolder = LoadLibs.extractTessResources("tessdata");
//Set the tessdata path
instance.setDatapath(tessDataFolder.getAbsolutePath());
instance.setLanguage("eng");
try {
String result = instance.doOCR(imageFile);
return result;
} catch (TesseractException e) {
System.err.println(e.getMessage());
return "this is an error" ;
}
}
}
Forword: your exception handling is horrific. Don't return an error message when your caller is expecting the OCR string. Stick to the JAVA style. In case of an error - throw an EXCEPTION!
Next: you never actually use the "filePath" parameter. This is clearly a bug.
You first need to ask yourself WHAT to test. Is it the "imageService" method you want to test? Then create a second class and from there, you would test your method. Within this test class, you would take an example file, call your imageService and compare the result with what you would expect. Those kind of comparisons are done with Assert-statements. Please check the jUnit docs for more detail.

Unable to retrieve JaCoCo coverage from exec file via Java API

We have JaCoCo for coverage. Some tests spawn a new java process for which I add the jacocoagent arguments and I get the expected jacoco.exec. Each file has a different path.
i.e. -javaagent:path/jacoco.jar=destfile=path/to/output.exec
I merge those and generate a report in which they correctly show as covered from those external processes.
Later I try to use the merged.exec using the Java API but I can't get coverage on those methods to perform some internal calculations.
In some cases I found that there might be multiple class coverage records for certain line (I assume depending on how many times that particular line was executed) so I use the following methods to get the best coverage out of those:
private List<IClassCoverage> getJacocoCoverageData(ExecutionDataStore
execDataStore,
String classFile) throws IOException
{
List<IClassCoverage> result = new ArrayList<>();
logger.debug("Processing coverage for class: " + classFile);
final CoverageBuilder coverageBuilder = new CoverageBuilder();
final Analyzer analyzer = new Analyzer(execDataStore, coverageBuilder);
File file = new File(this.workspaceRoot, classFile);
logger.debug("Analyzing coverage in: " + file);
if (file.exists())
{
try (FileInputStream fis = new FileInputStream(file))
{
analyzer.analyzeClass(fis, file.getAbsolutePath());
}
Iterator<IClassCoverage> it = coverageBuilder.getClasses().iterator();
while (it.hasNext())
{
result.add(it.next());
}
}
return result;
}
private IClassCoverage getBestCoverage(List<IClassCoverage> coverage,
int workingCopyLine)
{
IClassCoverage coverageData = null;
for (IClassCoverage cc : coverage)
{
ILine temp = cc.getLine(workingCopyLine);
if (coverageData == null
|| temp.getStatus()
> coverageData.getLine(workingCopyLine).getStatus())
{
coverageData = cc;
}
}
return coverageData;
}
Somehow I only find not covered coverage data. Both the reports and the methods above look at the same merged.exec file.
This turned out to be something completely unrelated to the JaCoCo file. The code above worked fine.

Can't co-create object / Can't find moniker | Jacob

When creating an ActiveXComponent using JACOB I get the following error.
com.jacob.com.ComFailException: Can't co-create object
at com.jacob.com.Dispatch.createInstanceNative(Native Method)
at com.jacob.com.Dispatch.<init>(Dispatch.java:99)
at com.jacob.activeX.ActiveXComponent.<init>(ActiveXComponent.java:58)
at com.paston.jacobtest.RidderIQ.main(RidderIQ.java:30)
The COM object which I need to use from a program which doesn't register its DLLs by itself during installation.
To register the DLL I used the 64bit version of RegAsm according to this article that could help. Also, I tried to load every DLL in of the external program because I suspected that there could be "something" wrong with loading the dependencies.
Here is my current code:
public static void main(String[] args) {
String dllDir = "C:\\Program Files (x86)\\Ridder iQ Client\\Bin\\";
File folder = new File( dllDir );
for (final File fileEntry : folder.listFiles()) {
String str = fileEntry.getName();
if (str.substring(str.lastIndexOf('.') + 1).equals("dll")) {
System.out.println(fileEntry.getName());
System.load(dllDir + str);
}
}
try {
ActiveXComponent example = new ActiveXComponent("RidderIQSDK");
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
When changing the name to the clsid I get a different exception.
com.jacob.com.ComFailException: Can't find moniker
at com.jacob.com.Dispatch.createInstanceNative(Native Method)
at com.jacob.com.Dispatch.<init>(Dispatch.java:99)
at com.jacob.activeX.ActiveXComponent.<init>(ActiveXComponent.java:58)
at com.paston.jacobtest.RidderIQ.main(RidderIQ.java:28)
I got JACOB to work with my code in another test using the system's Random object.
ActiveXComponent random = new ActiveXComponent("clsid:4E77EC8F-51D8-386C-85FE-7DC931B7A8E7");
Object obj = random.getObject();
Object result = Dispatch.call((Dispatch) obj, "Next");
System.out.println("Result: "+result);
I tried all solution and finally succeeded to crack the code related to JACOB. Create your code as per below sample code.
public static void main(String[] args) {
String libFile = System.getProperty("os.arch").equals("amd64") ? "jacob-1.17-x64.dll" :"jacob-1.17-x86.dll";
try{
/**
* Reading jacob.dll file
*/
InputStream inputStream = certificatemain.class.getResourceAsStream(libFile);
/**
* Step 1: Create temporary file under <%user.home%>\AppData\Local\Temp\jacob.dll
* Step 2: Write contents of `inputStream` to that temporary file.
*/
File temporaryDll = File.createTempFile("jacob", ".dll");
FileOutputStream outputStream = new FileOutputStream(temporaryDll);
byte[] array = new byte[8192];
for (int i = inputStream.read(array); i != -1; i = inputStream.read(array)){
outputStream.write(array, 0, i);
}
outputStream.close();
/* Temporary file will be removed after terminating-closing-ending the application-program */
System.setProperty(LibraryLoader.JACOB_DLL_PATH, temporaryDll.getAbsolutePath());
LibraryLoader.loadJacobLibrary();
ActiveXComponent comp=new ActiveXComponent("Com.Calculation");
System.out.println("The Library been loaded, and an activeX component been created");
int arg1=100;
int arg2=50;
//using the functions from the library:
int summation=Dispatch.call(comp, "sum",arg1,arg2).toInt();
System.out.println("Summation= "+ summation);
}catch(Exception e){
e.printStackTrace();
}
}
Now let me tell you how to register your DLL. I also followed same article you mentioned but not working when you are dealing with applet.
Go to x86 framework using command line.
C:\Windows\Microsoft.NET\Framework\v2.0.50727
to register do same as
regasm.exe path_to_your_dll.dll /codebase
Don't pass any other flag except /codebase. You are done with it... Still you find any problem let me know...

Categories

Resources