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
Related
I just finished an assignment for class and uploaded it to a website desgined to give the program the argument when uploaded and run. Since the site just shows your output and the coding goes "behind the scenes" just for the professor to read I cant see it actually running. I was wondering how I woud input an Args.txt file into netbeans so that I may know how to do it and test projects on my own in the future. Here is the output code for my file :
public static void main(String[] args){
In in = new In(args[0]);
Graph G = new Graph(in);
GraphProperties gp = new GraphProperties(G);
System.out.println("diameter: " + gp.diameter());
System.out.println("radius: " + gp.radius());
System.out.println("center: " + gp.center());
}
I tried putting it into properties but didn't get anywhere.
Thanks in advance!
Following code gets stuck(which I think is blocking I/O) many times (works some time).
def static executeCurlCommand(URL){
def url = "curl " + URL;
def proc = url.execute();
def output = proc.in.text;
return output;
}
But when I changes the code to
def static executeCurlCommand(URL){
def url = "curl " + URL;
def proc = url.execute();
def outputStream = new StringBuffer();
proc.waitForProcessOutput(outputStream, System.err)
return outputStream.toString();
}
it works fine every time. I am not able to understand why does the 1st way i.e taking input by proc.in.text hangs some time? Does not look an environment specific problem as I tried it on Windows as well as cygwin.
To test/run the above method I have tried -
public static void main(def args){
def url = 'http://mail.google.com';
println("Output : " + executeCurlCommand(url));
}
I have seen multiple questions on SO and all provide the 2nd approach. Although it works good I wish I could know whats wrong with 1st approach ? Has anyone has encountered this scenario before?
The first approach fills a buffer up and then blocks waiting for more room to write output to.
The second approach streams output from the buffer via a separate thread as the process is running, so the process doesn't block.
NOTE: Thanks to user2602219 and Andrew Thompson I've solved my problem. I wish I could approve both answers right and vote up.
I've searched a lot. I've found something but they were not suitable for me.
All I want is write
Hello
World
as seen. But in my txt file it shows HelloWorld
try{
JTextArea area = new JTextArea();
String path = folder+"/"+name+".txt";
BufferedWriter output = new BufferedWriter(new FileWriter(path));
area.write(output);
output.close();
}
catch(IOException ex){}
The code above works fine. However, I've to do something before writing.
I've an encryption method (called enc). It takes a string and replaces letters wit another letters.
For example:
String text = "ABC";
String enc_text = enc(text);
//enc_text is now "ZXW";
But here is the thing. JTextArea.write looks for a "Writer" but I have to write a string because my encrypter returns a string.
Long story short. How to make
Hello
World
to this
Gteeu
Wuazx
Take the unencrypted string from the first text area.
Encrypt it.
Put the encrypted string in a second text area that is not immediately visible to the end user.
Use the JTextCompnent.write(..) method on the encrypted text area.
Try to use this:
String text = "Hello" + "\nWorld";
\n is a new line.
Did you try to read each line separately and then write it on the desired txt file? This way you could use "\n" to write on a new line. Another solution that came to my mind is using the following method:
String s = "";
s = s.format(something + "\n");
This way you would have lines in the string itself :)
static void writeStringToFile(File file, String data)
which allows you to write text to a file in one method call.
or use
FileUtils.writeStringToFile(new File("test.txt"), "Hello File");
I have a problem about creating a textfile with the name I want.
I want to create a textfile named : 'username' Subjects.
private void saveSubjects(){
RegisterFrame r = new RegisterFrame();
String username = r.txtUser.getText();;
try{
FileWriter f = new FileWriter(username + "" + "Subjects" + ".txt", true);
String subjects[] = lstSubjects.getItems();
for(int i = 0; i<subjects.length; i++){
f.write(subjects[i] + "\r\n");
}
f.close();
JOptionPane.showMessageDialog(null, "Data saved!", "Data Saved", JOptionPane.INFORMATION_MESSAGE);
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Nothing Inputted!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
I want to get the username from RegisterFrame as it is inputted there but it's not working.
I know it's a simple thing but I'm still a beginner in this. How can I solve this?
Thanks in advance
try this:
String username = r.txtUser.getText();
System.out.println("The loaded username is: " + username);
then you will see where your problem is : writing into the file OR getting the username text.
If the problem is in getting the text, consider other way of getting it or modify the question by removing the file write part and specifiing the username getting part.
Otherwise, IDK where the error is.
BTW: how is it not working? the file is not created at all? do you see any errors? the file has wrong name? please specify
Your code for writing the file seems to be fine. Based on your code I tried this which worked perfectly:
public static void main(String[] args) {
FileWriter f = null;
try {
f = new FileWriter("Subjects.txt", true);
String subjects[] = {"subject1", "subject2"};
for (String subject : subjects) {
f.write(subject + "\r\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(f);
}
}
I'd say your problem is elsewhere.
Please note that best practice dictates that Closeable objects such as FileWriter should be closed in a finally block
Assuming new RegisterFrame() starts up a GUI window, the issue is your code runs before you have a chance to type in your name. Instead you need to use event listeners to capture the contents of text fields, otherwise the code to get the name runs immediately after the window opens, long before you have a chance to type anything in.
The timeline is like this:
RegisterFrame starts a new thread to display the GUI without blocking your code
Your code immediately pulls "" from txtUser, which is of course empty
Now you type your name in
Nothing happens, because nothing in your code is paying attention to that action
Instead, it should be:
RegisterFrame starts a new thread to display the GUI without blocking your code
The method returns, or starts doing work that isn't dependent on the GUI
Now you type your name in
An event listener is triggered from the new thread, and the associated action to get the name and write to a file is executed
You have to decide what sort of listener makes sense for your use case, for instance you might want to wait until the user clicks a button (that says "Submit" or "Write File" for instance) and register an ActionListener on that button. Then you put your username polling and file writing behavior in that action* and you're golden!
*I should add that in truth you want to do as little as possible in ActionListeners, and it would be better to check if the username is not empty, then pass the actual work off to another thread, for instance with a SwingWorker, but for your purposes I suspect it will be alright to not worry about that.
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.