Please help me with JUnit test cases for the code below - java

I want to know the JUnit test cases for the following program.please help. I have not included the main method here. Want to know the JUnit test cases for the url() method in the code. This code is to read HTML from a website and save it in a file in local machine
package Java3;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Urltohtml
{
private String str;
public void url() throws IOException
{
try
{
FileOutputStream f=new FileOutputStream("D:/File1.txt");
PrintStream p=new PrintStream(f);
URL u=new URL("http://www.google.com");
BufferedReader br=new BufferedReader(new InputStreamReader(u.openStream()));
//str=br.readLine();
while((str=br.readLine())!=null)
{
System.out.println(str+"\n");
p.println(str);
}
}
catch (MalformedURLException ex)
{
Logger.getLogger(Urltohtml.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

I would rename that class to UrlToHtml and write a single JUnit test class UrlToHtmlTest.
Part of the reason why you're having problems testing this is that the class is poorly designed and implemented:
You should pass in the URL you want to scrape, not hard code it.
You should return the content as a String or List, not print it to a file.
You might want to throw that exception rather than catch it. Your logging isn't exactly "handling" the exceptional situation. Let it bubble out and have clients log if they wish.
You don't need that private data member; return the contents. That lets you make this method static.
Good names matter. I don't like what you have for the class or the method.
Why are you writing this when you could use a library to do it?
Here's what the test class might look like:
public class UrlToHtmlTest {
#Test
public void testUrlToHtml() {
try {
String testUrl = "http://www.google.com" ;
String expected = "";
String actual = UrlToHtml.url(testUrl);
Assert.assertEquals(expected, actual);
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
}

Related

How to integrate karate with testrail

I am new to Java and using karate for API automation. I need help to integrate testrail with karate. I want to use tags for each scenario which will be the test case id (from testrail) and I want to push the result 'after the scenario'.
Can someone guide me on this? Code snippets would be more appreciated. Thank you!
I spent a lot of effort for this.
That's how I implement. Maybe you can follow it.
First of all, you should download the APIClient.java and APIException.java files from the link below.
TestrailApi in github
Then you need to add these files to the following path in your project.
For example: YourProjectFolder/src/main/java/testrails/
In your karate-config.js file, after each test, you can send your case tags, test results and error messages to the BaseTest.java file, which I will talk about shortly.
karate-config.js file
function fn() {
var config = {
baseUrl: 'http://111.111.1.111:11111',
};
karate.configure('afterScenario', () => {
try{
const BaseTestClass = Java.type('features.BaseTest');
BaseTestClass.sendScenarioResults(karate.scenario.failed,
karate.scenario.tags, karate.info.errorMessage);
}catch(error) {
console.log(error)
}
});
return config;
}
Please dont forget give tag to scenario in Feature file.
For example #1111
Feature: ExampleFeature
Background:
* def conf = call read('../karate-config.js')
* url conf.baseUrl
#1111
Scenario: Example
Next, create a runner file named BaseTests.java
BaseTest.java file
package features;
import com.intuit.karate.junit5.Karate;
import net.minidev.json.JSONObject;
import org.junit.jupiter.api.BeforeAll;
import testrails.APIClient;
import testrails.APIException;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
public class BaseTest {
private static APIClient client = null;
private static String runID = null;
#BeforeAll
public static void beforeClass() throws Exception {
String fileName = System.getProperty("karate.options");
//Login to API
client = new APIClient("Write Your host, for example
https://yourcompanyname.testrail.io/");
client.setUser("user.name#companyname.com");
client.setPassword("password");
//Create Test Run
Map data = new HashMap();
data.put("suite_id", "Write Your Project SuitId(Only number)");
data.put("name", "Api Test Run");
data.put("description", "Karate Architect Regression Running");
JSONObject c = (JSONObject) client.sendPost("add_run/" +
TESTRAİL_PROJECT_ID, data);
runID = c.getAsString("id");
}
//Send Scenario Result to Testrail
public static void sendScenarioResults(boolean failed, List<String> tags, String errorMessage) {
try {
Map data = new HashMap();
data.put("status_id", failed ? 5 : 1);
data.put("comment", errorMessage);
client.sendPost("add_result_for_case/" + runID + "/" + tags.get(0),
data);
} catch (IOException e) {
e.printStackTrace();
} catch (APIException e) {
e.printStackTrace();
}
}
#Karate.Test
Karate ExampleFeatureRun() {
return Karate.run("ExampleFeatureRun").relativeTo(getClass());
}
}
Please look at 'hooks' documented here: https://github.com/intuit/karate#hooks
And there is an example with code over here: https://github.com/intuit/karate/blob/master/karate-demo/src/test/java/demo/hooks/hooks.feature
I'm sorry I can't help you with how to push data to testrail, but it may be as simple as an HTTP request. And guess what Karate is famous for :)
Note that values of tags can be accessed within a test, here is the doc for karate.tagValues (with link to example): https://github.com/intuit/karate#the-karate-object
Note that you need to be on the 0.7.0 version, right now 0.7.0.RC8 is available.
Edit - also see: https://stackoverflow.com/a/54527955/143475

Exception while calling Parser method outside main class

In my application I have a method which I cant execute without main method. It only runs inside the main method. When I call that method inside my servlet class. It show an exception
My class with Main Method
package com.books.servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.HashSet;
import java.util.Set;
import opennlp.tools.cmdline.parser.ParserTool;
import opennlp.tools.parser.Parse;
import opennlp.tools.parser.Parser;
import opennlp.tools.parser.ParserFactory;
import opennlp.tools.parser.ParserModel;
public class ParserTest {
// download
public void download(String url, File destination) throws IOException, Exception {
URL website = new URL(url);
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
public static Set<String> nounPhrases = new HashSet<>();
private static String line = "The Moon is a barren, rocky world ";
public void getNounPhrases(Parse p) {
if (p.getType().equals("NN") || p.getType().equals("NNS") || p.getType().equals("NNP")
|| p.getType().equals("NNPS")) {
nounPhrases.add(p.getCoveredText());
}
for (Parse child : p.getChildren()) {
getNounPhrases(child);
}
}
public void parserAction() throws Exception {
// InputStream is = new FileInputStream("en-parser-chunking.bin");
File modelFile = new File("en-parser-chunking.bin");
if (!modelFile.exists()) {
System.out.println("Downloading model.");
download("https://drive.google.com/uc?export=download&id=0B4uQtYVPbChrY2ZIWmpRQ1FSVVk", modelFile);
}
ParserModel model = new ParserModel(modelFile);
Parser parser = ParserFactory.create(model);
Parse topParses[] = ParserTool.parseLine(line, parser, 1);
for (Parse p : topParses) {
// p.show();
getNounPhrases(p);
}
}
public static void main(String[] args) throws Exception {
new ParserTest().parserAction();
System.out.println("List of Noun Parse : " + nounPhrases);
}
}
It gives me below output
List of Noun Parse : [barren,, world, Moon]
Then I commented the main method and. Called the ParserAction() method in my servlet class
if (name.equals("bkDescription")) {
bookDes = value;
try {
new ParserTest().parserAction();
System.out.println("Nouns Are"+ParserTest.nounPhrases);
} catch (Exception e) {
}
It gives me the below exceptions
And below error in my Browser
Why is this happening ? I can run this with main method. But when I remove main method and called in my servlet. it gives an exception. Is there any way to fix this issue ?
NOTE - I have read below instructions in OpenNLP documentation , but I have no clear idea about it. Please help me to fix his issue.
Unlike the other components to instantiate the Parser a factory method
should be used instead of creating the Parser via the new operator.
The parser model is either trained for the chunking parser or the tree
insert parser the parser implementation must be chosen correctly. The
factory method will read a type parameter from the model and create an
instance of the corresponding parser implementation.
Either create an object of ParserTest class or remove new keyword in this line new ParserTest().parserAction();

Incomplete java.net.URL.openStream() stream

I’m using java.net.URL.openStream() to access a HTTPS resource. The returned stream is incomplete for some URLs: for the example below, it yields a 1,105,724 byte-file whereas the same URL accessed from a browser yields a 5,755,858 byte-file (even when "disabling" Content-Encoding).
And it doesn’t even throw an exception.
What am I missing?
import static java.nio.file.Files.copy;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Paths;
public class Test {
public static void main(String... args) throws IOException {
try (final InputStream in = new URL(
"https://upload.wikimedia.org/wikipedia/commons/9/95/Germany_%28orthographic_projection%29.svg").openStream()) {
copy(in, Paths.get("germany.svg"));
}
}
}
Edit
I’ve tested this code a lot of times (on different networks, but always on JRE 1.8.0_60 / Mac OS X 10.11.4), and sometimes it’s suddenly "starting to work".
However, switching to another of my problematic URLs (e.g. "https://upload.wikimedia.org/wikipedia/commons/c/ce/Andorra_in_Europe_%28zoomed%29.svg") enables me to reproduce the issue.
Does this mean that it is a server issue? I’ve never seen it on a browser though.
It's working fine.
As others have suggested there may be a problem with your network, try connecting to another network.
package test;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public class TestMain2 {
public static void main(String[] args) {
System.out.println("Started");
try (final InputStream in = new URL(
"https://upload.wikimedia.org/wikipedia/commons/9/95/Germany_%28orthographic_projection%29.svg")
.openStream()) {
Path outputFile = Paths.get("test.svg");
Files.copy(in, outputFile, StandardCopyOption.REPLACE_EXISTING);
System.out.println("Output file size : " + outputFile.toFile().length());
System.out.println("Finished");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Output
Started
Output file size : 5755858
Finished

MalformedURLException in java application

i wrote a simple program which is in my book.
but i'm getting the MalformedURLException exception.This is my code
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
public class ImageGreet{
public static void main(String []args){
URL imageLocation = new URL("http://horstmann.com/java4everyone/duke.gif");
JOptionPane.showMessageDialog(null,"Hello","Title",JOptionPane.PLAIN_MESSAGE,new ImageIcon(imageLocation));
}
}
but my friend said he got it right with the same code.
what's wr9ong with my code? Is it because of the internet connection(I'm using a dial-up connection)
I
Java uses the concept of checked Exceptions. You need to put this code inside a try/catch block, since it is bound to throw a MalformedURLException. Something like
URL imageLocation = null;
try {
imageLocation = new URL("http://horstmann.com/java4everyone/duke.gif");
} catch (MalformedURLException mue) {
mue.printStackTrace();
}
Or let the main method throws the Exception like :
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
public class ImageGreet{
public static void main(String []args) throws MalformedURLException {
URL imageLocation = new URL("http://horstmann.com/java4everyone/duke.gif");
JOptionPane.showMessageDialog(null,"Hello","Title",JOptionPane.PLAIN_MESSAGE,new ImageIcon(imageLocation));
}
}
catch the MalformedURLException using try and catch block
try {
URL imageLocation = new URL("http://horstmann.com/java4everyone/duke.gif");
JOptionPane.showMessageDialog(null,"Hello","Title",
JOptionPane.PLAIN_MESSAGE,new ImageIcon(imageLocation));
}
catch (MalformedURLException e) {
// new URL() failed
// ...
}
Your internet connection would not cause that Exception. (If your URL did not exist, Java would throw an IOException, probably a FileNotFoundException, per URLConnection documentation.) In fact, your code isn't throwing an Exception at all! What you're seeing is a compile error:
$ javac ImageGreet.java
ImageGreet.java:7: error: unreported exception MalformedURLException; must be caught or declared to be thrown
URL imageLocation = new URL("http://horstmann.com/java4everyone/duke.gif");
^
1 error
When Java tries to turn your program from source code into machine code, it finds a problem, so it stops and asks you to fix it. Your code hasn't run yet -- Java's warning you that there's a problem with your program's source code. (If you're running an IDE, this will show up in a "problems" pane, as opposed to an error message from javac.)
The issue is that you need to catch the MalformedURLException in your code, or declare that main throws MalformedURLException. For example:
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
public class ImageGreet{
public static void main(String []args) throws MalformedURLException {
URL imageLocation=new URL("http://horstmann.com/java4everyone/duke.gif");
JOptionPane.showMessageDialog(null,"Hello","Title",JOptionPane.PLAIN_MESSAGE,new ImageIcon(imageLocation));
}
}
Note that I've added throws MalformedURLException to the end of your main method, which is the latter of the solutions I suggested above. That tells Java that your main method may propagate an Exception of type MalformedURLException.
Since Java has checked exception you have to add throws MalformedURLException to your methods header or you have to write the method logic inside try/catch blocks.

ClassNotFoundException happens during calling ObjectInputStream.readobject in Android

I want to read object from Android internal storage.
The following is my code.
I write a static function for reading object from file in the same class.
No idea why this exception happen .
Really appreciate if you could give some suggestions.
thanks.
package com.crescent.programmercalculator;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import android.util.Log;
import android.content.Context;
public class CalculateConfigurations implements Serializable{
static String configLocation="configFile";
public short radix;
CalculateConfigurations(){
radix=16;
}
public static CalculateConfigurations loadObjectFromFile(Context context){
try {
FileInputStream fis = context.openFileInput(configLocation);
ObjectInputStream is = new ObjectInputStream(fis);
CalculateConfigurations config = (CalculateConfigurations) is.readObject();
is.close();
fis.close();
return config;
} catch (FileNotFoundException e) {
// first use case
Log.v("CalculateConfigurations", "first init for configuration file");
return new CalculateConfigurations();
} catch (IOException e) {
e.printStackTrace();
Log.e("CalculateConfigurations", "Fatal error, configuration file may be broken");
return new CalculateConfigurations();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
Log.e("CalculateConfigurations", "Fatal error, unknown");
return new CalculateConfigurations();
}
}
}
ClassNotFoundException
this is in most cases some mixup in your xml-files. If you post both stacktrace and the proper xml-file, it is easy to fix it!
Read on readObject
Exceptions are thrown for problems with the InputStream and for
classes that should not be deserialized. All exceptions are fatal to
the InputStream and leave it in an indeterminate state; it is up to
the caller to ignore or recover the stream state.
Since you are trying to read an android internal library, it cannot be casted to your custom Class. Hence the ClassNotFoundException.
Hope this helps.
I encounter the same problem today. I don't know how the serialization/deserialization is done but I notice that it is very unstable process.
If you serialize some objects and put the memory, you cannot change the data type/class name easily.. If it throws class not found exception like this, remove the app from device and install again. I hope, it helps some developers :)

Categories