I'm using assert equals to compare two numbers
Assert.assertEquals("My error message", First , Second);
Then, when I generate the Test Report I get
"My error message expected (First) was (Second)"
How can I customize the part I've put in italic? And the format of the numbers?
You can use something like this:
int a=1, b=2;
String str = "Failure: I was expecting %d to be equal to %d";
assertTrue(String.format(str, a, b), a == b);
The message is hard-coded in the Assert class. You will have to write your own code to produce a custom message:
if (!first.equals(second)) {
throw new AssertionFailedError(
String.format("bespoke message here", first, second));
}
(Note: the above is a rough example - you'll want to check for nulls etc. See the code of Assert.java to see how it's done).
Thanks to your answer I've found in the Assert class this
static String format(String message, Object expected, Object actual) {
String formatted= "";
if (message != null && !message.equals(""))
formatted= message + " ";
String expectedString= String.valueOf(expected);
String actualString= String.valueOf(actual);
if (expectedString.equals(actualString))
return formatted + "expected: "
+ formatClassAndValue(expected, expectedString)
+ " but was: " + formatClassAndValue(actual, actualString);
else
return formatted + "expected:<" + expectedString + "> but was:<"
+ actualString + ">";
}
I guess I can't modify Junit Assert class, but I can create a new class in my project with the same name, just changing format, am I right? Or I can just change format in my class and it will affect the Exception thrown?
Related
How can I automatically print without poping up dialog box or automatically accept print dialog? Here is some of my code:
if ("OUT".equals(rs.getString("empattendance"))) {
String date = dft.format(dNow);
String time = tft.format(dNow);
textArea.setText(date + "\n" + "\n" +
fullname +"\n" +
"Time In: " + time + "\n" +
"Status: "+ statusin +
"\n" +
"\n" +
"____________________\n" +
" Sign by Supervisor");
try {
//printing
Boolean complete = textArea.print();
if(complete){
}
else{
}
} catch (PrinterException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
and here's the screenshot of the current behaviour.
thanks
When I look at your code I have few thoughts before answer.
1) Do not use String. Better for comparing stuff is Enumerators I believe.
2) If you would like to set text to textArea previously create some method using StringBuilder for example which will be creating the String you would like to set. Joshua Bloch says
Item 15: minimize mutability (...) If a client requires performing expensive multi-stage operations on your class, expose them as primitive methods, or provide a mutable companion class (like StringBuilder for String).
And take a look at this topic for more.
3) To print data from textArea if I were you I would try to use this.
I believe that would help you
I can't figure out how to use variables in HTML, string is a variable in this case.
JOptionPane.showMessageDialog(null,"<html>Error #1<br> + string +</html>","Error",JOptionPane.PLAIN_MESSAGE);
this output: Error #1 + string
JOptionPane.showMessageDialog(null,"<html>Error #1<br></html>" + string ,"Error",JOptionPane.PLAIN_MESSAGE);
this output: Error #1
is there a way to use string variables in HTML?
Do you want something like
"<html>Error #1<br>" + string + "</html>"
?
If you want to concatenate the string variable to the html you have there, it must be outside the quotes, otherwise it will be treated as a literal, as in your example.
JOptionPane.showMessageDialog(
null,
"<html>Error #1<br>" + string + "</html>",
"Error",
JOptionPane.PLAIN_MESSAGE);
Though note that logically JOptionPane.PLAIN_MESSAGE should be JOptionPane.ERROR_MESSAGE.
You need to do: "<html>Error #1<br>" + string + "</html>"
A string literal in java consists of zero or more characters enclosed in double quotes. So anything satisfies this condition will also be regarded as string too. You will need to close the String before appending the string.
So if the string = "Hi to stack":
Then "<html>Error #1<br>" + string + "</html>" will result in:
"<html>Error #1<br>Hi to stack</html>"
I am trying to create a way of retrieving from a hashtable an authorID for the articleName that the user enters. Here is the code that is activated on the client's side when the user presses a button:
public String getAuthorID() // returns a String
{
try
{
articleName = txtArticleName.getText();
argAuthorID = new Vector();// create vector for the args
argAuthorID.addElement(articleName);// name to search for to get AuthorID
// make the call to the server
authorIDVector = (Integer)client.execute("GetSize.sendAuthorID", argAuthorID);
System.out.println(argAuthorID);
}
catch (XmlRpcException exception) {
System.err.println("JavaClient: XML-RPC Consumer Fault #" +
Integer.toString(exception.code) + ": " +
exception.getCause() + "" + exception.toString());
} catch (Exception exception) {
System.err.println("JavaClient: XML-RPC Consumer Fault #" + exception.toString());
}
String StrAuthorID = Integer.toString(authorID); // Cast AuthorID to String
return StrAuthorID;
}
This is the method on the server side:
public int sendAuthorID(String articleNameRequest) {
// get info from the hashtable
aNumber = (Integer) theHashtable.getAuthorID(articleNameRequest); // was this.
return aNumber;
}
This is the code in the class that contains the hashtable:
public int getAuthorID(String articleName)
{
int intfoundit;
String foundit = (String)hashtab.get(articleName);
System.out.print(foundit);
intfoundit = Integer.parseInt(foundit);
System.out.print(foundit);
System.out.print(intfoundit);
return intfoundit;
}
The program can retrieve the AuthorID but won't input it into the textbox. Via testing I discovered that the exception was thrown by this code:
catch (XmlRpcException exception) {
System.err.println("JavaClient: XML-RPC Consumer Fault #" +
Integer.toString(exception.code) + ": " +
exception.getCause() + "" + exception.toString());
This is the error that is given:
'JavaClient: XML-RPC Consumer Fault #0:
nullorg.apache.xmlrpc.XmlRpcException: java.lang.Exception:
java.lang.NumberFormatException: For input string: " 3377"'
UPDATE: removed the space before the ID number in the hashtable and it doesn't throw an error anymore but it still isn't inputting the ID number into the textbox instead it just inputs a '0'
It seems to be failing in cases when you have spaces in your string. As we can see in your exception trace that parseInt failed to parse " 3377" and it threw NumberFormatException while executing:
intfoundit = Integer.parseInt(foundit);
So you may try to trim the string and see whether it solves your problem:
intfoundit = Integer.parseInt(foundit.trim());
Better you should do the trim where you are saving/putting the key/value in the hashtable.
The answer to the first problem was space before ID number on the hashtable because the space couldn't be converted to an Integer.
The answer to the second problem was that the following line was trying to convert the wrong variable
String StrAuthorID = Integer.toString(authorID); // Cast AuthorID to String
because the Integer was in the AuthorID variable
I corrected this by changing
authorIDVector = (Integer)client.execute("GetSize.sendAuthorID", argAuthorID);
to
authorID = (Integer)client.execute("GetSize.sendAuthorID", argAuthorID);
I am using following code for local storage.
for(int i=0; i< files.length; i++)
{
System.out.println("base = " + files[i].getName() + "\n i=" +i + "\n");
AudioFile f = AudioFileIO.read(files[i]);
Tag tag = f.getTag();
//AudioHeader h = f.getAudioHeader();
int l = f.getAudioHeader().getTrackLength();
String s1 = tag.getFirst(FieldKey.ALBUM);
out.print("writeToStorage("+s1+","+s1+");");
}
getting uncaught syntex erroe: unexpected identifer as a error.
Im guessing you meant java rather than javascript?
Your unexpected identifier is here out.println you need System. infront of it.
The reason for this is that out is not defined in your code. You need to access it by using the static variable in the System class. Hence why you use System.out.
Alternatley you could set a variable out to be equal to System.out for shorthand, although I don;t tend to. But this can allow you to switch out to a different type of output stream without having to refactor your code much.
Have you added following ?
import static java.lang.System.out;
Probably you need to output "s in the last line to surround the s1 values.
"writeToStorage("+s1+","+s1+");"
->
"writeToStorage('"+s1+"','"+s1+"');"
Btw for the same reason you have to fix the other line too:
"base = " + files[i].getName() + "...
->
"base = '" + files[i].getName() + "'...
I have a function that accepts a message in String form. The message looks like this : "HTTP/1.1 GET /1/ \n"
I have been using the java.String.split method to break down the string into three smaller substrings, version, command, and number. Then I reconstruct the oringal string from the substrings and output it.
However, when I run teh function the program results in ArrayIndex out of bounds : 1, but still functions properly. But when I run the program step by step in the debugger (netbeans) the program does not result in the ArrayIndex out of bounds nonesense and functions as normal
Any suggestions?
Sam
String output = "";
String[] tokens = clientMessage.split(" ");
String version = tokens[0];
String command = tokens[1];
String potNum = tokens[2];
output = version + " " + command + " " + potNum;
EDIT yes, the program is multithreaded, the clientMsessage string contains "HTTP/1.1 GET /1/ \n" all the time, the value fo clientMessage never changes. The clientMessage is a string sent from a client program and then processed on the server and the output is snet back tot eh client but I keep getting the array errors
I suggest you print out/log your inputs. I suspect you are doing something differently when you debug your program. Its possible this works the first time you call it but when its called again, it fails.
Add before the split.
System.out.println("clientMessage >" + clientMessage +"<");
If your output looks like
clientMessage >HTCPCP/1.0 PROPFIND /1/<
clientMessage >HTCPCP/1.0 PROPFIND /1/<
clientMessage ><
It appears you have an empty request message. I imagine this means the client will not be sending more requests and you have to handle this differently.
ArrayIndexOutOfBounds arises when you are accessing index of an array which does not have any values means in your case tokens[1] does not exists. When debugging are you using same string as input??
Sorry this is not an answer but just an additional question to find what is actually wrong and comments are too small to put that much code. The following works for me, so one of your asumptions is wrong:
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
String clientMessage = "HTTP/1.1 GET /1/ \n";
String[] tokens = clientMessage.split(" ");
String version = tokens[0];
String command = tokens[1];
String potNum = tokens[2];
System.err.println(version + " " + command + " " + potNum);
}
}
It runs OK on my side. I would have to guess that sometimes clientMessage is a value that does not contain enough spaces to be seperated in 3 parts.
Perhaps there is more to the code than you are including here. I put your code in a class as follows and it compiles and runs without error. Is there something missing?
public class Andrew {
public static void main(String args[]) {
String output = "";
String clientMessage = "HTTP/1.1 GET /1/ \n";
String[] tokens = clientMessage.split(" ");
String version = tokens[0];
String command = tokens[1];
String potNum = tokens[2];
output = version + " " + command + " " + potNum;
System.out.println(output);
}
}