I am not familiar with JUnit so not sure if that's the problem of assertTrue(b_exception);, because if I put an System.out.println("something"); there, it would print out "something"... Thanks!!
Please note that it is pseudo code, focus on the logic.
b_exception = false;
try{
somethingThrowError();
}catch(Error e){
b_exception = true;
}
assertTrue(b_exception);
I don't know what the problem is with your code because you haven't stated how it fails to fulfill your expectations, but the correct idiom for testing that an exception is thrown is to use JUnit 4's annotations:
#Test(expected=SpecificError.class)
public void testError(){
somethingThrowError();
}
I can only guess that you are looking for this:
try{
somethingThrowError();
fail("Exception expected");
}catch(AsSpecificAsPossibleException e){
//should happen, OK
//optionally assert exception message, etc.
}
Also note that catching an Error is a bad idea, use as specific exception as you can.
UPDATE: #Michael Borgwardt's answer is actually even better, but only if there is nothing except a single line in your test (nothing else that can throw). Also #Test(expected does not allow you to perform extra exception message assertions (but should you?)
Not sure what you think is wrong with that code.
The assertTrue will always be executed, as will the System.out.println.
It - the assertTrue - will signal an error if the argument is not true, or "pass the test" if the argument is true.
Maybe you should use System.out.println("b_exception = " + b_exception); to see what is happening.
Related
when a function or method encouter error/invalid data, do return false or throw an exception?
Consider a class Loginer has such method :
public boolean login(String username){
//retrieve data...
if(username.equals(record.username)){
return true;
}
return false;
}
then at the main or some other class
String username = "ggwp";
if(Loginer.login(username)){
//successful login, show homepage...
new User(username);
} else {
//invalid username
}
won't it be inefficient as it has been checked two time with if-else statement, one in Loginer, and another one check for true again at main.
won't try catch will do the same? having the Loginer to throw an Exception:
public User login(String username){
//retrieve record data...
if(username.equals(record.username)){
return new User(username);
}
/* Exception if no record found for such username */
throw new MyException("invalid username");
}
then on the main:
String username = "ggwp2";
User theUser;
try{
//sucessful login
theUser = Loginer.login(username);
}catch(MyException e){
//invalid username
}
the try-catch need no check second time for true or false. (this example i use return User object, it could be void and return nothing but the point is, why use boolean which will eventual being check twice?)
some website sources say not to use try-catch for 'code jumping' but in this case it just do the same. (try-catch is just too similar to if-else statement)
So which is correct and why? please guide and sorry if this question is incorrect, im newbie to OO.
Short answer:
You should NEVER use try/catch for "control logic".
As Andy Turner said, "Use exceptions to handle exceptional conditions only."
This is equally true of all languages that support exceptions - not just Java. Useful article:
Best practices for exceptions
PS: try/catch is NOT "just similar" to "if/else". It has a different implementation, a different intent ... and it's FAR more expensive.
ADDITIONAL NOTE:
Exceptions: Why throw early? Why catch late?
https://softwareengineering.stackexchange.com/questions/231057/exceptions-why-throw-early-why-catch-late
In my experience, its best to throw exceptions at the point where the
errors occur. You do this because it's the point where you know the
most about why the exception was triggered.
As the exception unwinds back up the layers, catching and rethrowing
is a good way to add additional context to the exception. This can
mean throwing a different type of exception, but include the original
exception when you do this.
Eventually the exception will reach a layer where you are able to make
decisions on code flow (e.g a prompt the user for action). This is the
point where you should finally handle the exception and continue
normal execution.
With practice and experience with your code base it becomes quite easy
to judge when to add additional context to errors, and where it's most
sensible to actually, finally handle the errors.
Catch → Rethrow
Do this where you can usefully add more information that would save
a developer having to work through all the layers to understand the
problem.
Catch → Handle
Do this where you can make final decisions on what is an
appropriate, but different execution flow through the software.
Catch → Error Return
Whilst there are situations where this is appropriate, catching
exceptions and returning an error value to the caller should be
considered for refactoring into a Catch → Rethrow implementation.
I am using Java, Selenium Webdriver and Junit. Doing simple verification of title of Google , But it throws exception when Assertion fails I mean when title does not match.
Code :
public static void verifyTitle(String expectedTitle) {
//get the title of the page
String actualTitle = Base.getdriver().getTitle();
// verify title
assertThat(actualTitle, equalTo(expectedTitle));
}
I am calling in main method : verifyTitle("Hello");
Output :
> Exception in thread "main" java.lang.AssertionError: Expected:
> "Hello"
> but: was "Google" at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20) at
> org.junit.Assert.assertThat(Assert.java:956) at
> org.junit.Assert.assertThat(Assert.java:923) at
> Modules.Help.verifyTitle(Help.java:161) at
> Modules.Help.GUI(Help.java:152) at Modules.Help.main(Help.java:29)
It is checking everything proper but not sure why throwing exception? How can I print message like "Title does not match" instead of this exception.
Write this:
if (!Objects.equals(actualTitle, expectedTitle))
System.out.println("Title doesn't match.");
But why would you want to do that?
Selenium tests inform you when something is not as expected, automatically. Throwing an AssertError means failure, and that failure can be displayed nicely to humans. When you use System.out.println, you just print something, but the program continues as if there were no error.
That is expected behavior of JNunit! It will always throw exception when assert failed. Here is description of the method assertThat:
Asserts that actual satisfies the condition specified by matcher. If
not, an AssertionError is thrown with information about the matcher
and failing value.
You can try/catch the Error then print the message that you want.
try {
assertThat("a", equalTo("a"));
System.out.println("Title matched");
}
catch(Error e) {
System.out.println("Title does not match");
}
You should try the try catch, have a look here: http://beginnersbook.com/2013/04/try-catch-in-java/ I think it could help you ;)
Just study the javadoc for assertThat:
Asserts that actual satisfies the condition specified by matcher. If not, an AssertionError is thrown with information about the matcher and failing value.
The point is that when you are running with JUnit, the exception is catched; and translated to some nice printout. So, when you are working outside of a JUnit #Test; well; then some other code needs to try/catch ...
I have a problem with an Expectations block I have written in my test case:
new Expectations() {
{
mFindHandlerMock.findAll((Model) any, (Set<Id>) any, false);
if (!pWithRealData) {
result = Collections.emptySet();
} else {
result = pAllData;
}
times = 1;
Deencapsulation.invoke(mDb, "readSqlQuery", withAny(String.class));
result = "select * from realdata";
times = 1;
}
};
the test case crashes with:
java.lang.IllegalArgumentException: Invalid conditional statement inside expectation block
exactly here:
if (!pWithRealData) {
it's just a simple boolean that is false in this case.
I have absolutly no clue why the exception happens.
I already searched with google but found nothing helpful.
Could you help me?
From the JMockit release notes for version 1.14:
Enhancement: Conditionals and loops will now trigger an exception when found inside an expectation recording block, to prevent API misuse and to encourage simpler tests. See issue #97.
The GitHub issues related to this:
https://github.com/jmockit/jmockit1/issues/97
https://github.com/jmockit/jmockit1/issues/123
In the one issue they state that:
Yes, and this is as intended, to avoid tests getting too complicated when recording expectations. A full test was not shown, but it looks to me that recording the specific expectations directly would be better in this case.
In the JMockit source you can see which other types of conditionals and loops will throw that exception.
In short, from JMockit 1.14 onwards you are not allowed to have conditionals (such as if statements) and loops in the Expectation block.
How can I get the results of my JUnit assertions to be printed [to standard output]?
I have some tests like this:
#Test
public void test01()
{
Position p = getPositionAt('a', 1);
assertNotNull("a1 exists", p);
assertNotNull("figure exists a1", p.getFigure());
p = getPositionAt('a', 2);
assertNotNull("exists a2", p);
assertNull("figure exists a2", p.getFigure());
p = getPositionAt('b', 1);
assertNotNull("exists b1", p);
assertNull("figure exists b1", p.getFigure());
}
This is the printed output format I am hoping to get:
a1 exists -success
figure exists a1 -success
exists a2 -success
figure exists a2 -succcess
exists b1 -succcess
figure exists b1 -failed
Is there way to do this using runners and suites? Or does there exist any assertSuccess(), assertFailed() methods?
First, you have two issues not one. When an assertion fails, an AssertionError exception is thrown. This prevents any assertion past this point from being checked. To address this you need to use an ErrorCollector.
Second, I do not believe there is any way built in to JUnit to do this. However, you could implement your own methods that wrap the assertions:
public static void assertNotNull(String description, Object object){
try{
Assert.assertNotNull(description, object);
System.out.println(description + " - passed");
}catch(AssertionError e){
System.out.println(description + " - failed");
throw e;
}
}
All the assertXXX methods have a form that allows for displaying a String on error:
assertNotNull("exists a2", p); // prints "exists a2" if p is null
There is no particular value in printing a message on success.
EDIT
Junit typically provides 2 forms of an assert. To follow the example above, you can test for a null value in 1 of 2 ways:
assertNotNull(p)
or
assertNotNull("my message on failure", p)
The framework will print the error messages with no other effort required by you (it's provided by the framework).
To test for exceptions you would use the following pattern:
try{
someCall();
catch(Exception e){
fail(): // exception shouldn't happen, use assertTrue(true) if it should
}
Again, there are versions of these methods for adding a message
Check the API
One last resort option is to pair each assert with a corresponding System.out.println, though obviously that is less than ideal. Still, it will solve the problem if all else fails.
Existing Answers/Comments here contain enough info to understand how to print something based on JUnit assertions - but they also explain how doing so is probably not what you actually want to do, and is probably missing the point of running unit tests in the first place.
You should be viewing the results of the tests themselves, instead of trying to print something while you don't understand how/where to view test results themselves.
Now then how/where to view results themselves depends on how you are running your tests - you need to understand how you are running your tests, and then research how to view test results according to how you are running them. Here are a few (but not limited to) examples:
Running tests in IntelliJ
Running tests in Eclipse
Running tests on command line
Running tests in Jenkins
Is there a better way for catching specific Exception with a message then doing this:
try{
methodThatWillProbablyThrowASocketException();
} catch(SocketException e){
if(e.getMessage().contains("reset")){
// the connection was reset
// will ignore
} else{
throw e;
}
}
For example the HttpStatusException gives me the Method getStatusCode() where i can easily compare if the error status was 404 or 502 and the can decide what to do:
try{
methodThatWillProbablyThrowAHTTPException();
} catch(HttpStatusException e){
if(e.getStatusCode() == 404){
// not found, will not continue
}
if else(e.getStatusCode() == 502){
// server errror, try again
} else{
throw e;
}
}
Most other Exceptions dont give me prober Methods, just the Message.
So my question is, is it the right way to do it? With String compares? Or is there a better way?
Just do one thing .
Collect all types of exception that are likely to be occur for your project.
Make a separate class by extending Exception.
Override the getCause() method.
http://docs.oracle.com/javase/6/docs/api/java/lang/Throwable.html#getCause%28%29
public Throwable getCause()
Define codes you want for different exceptions Like null-pointer 101 ,, so on......
The use that class every where . So you have to write exception only once and you can use with as many projects.
After building the class it will be reusable for all your needs
If you getting new conditions, update this class only and all the things will be done
This is a better solution according to me...
This way you can get functionality for which you are looking. you have to make it by yourself.
Relying on code or status code is fine but relying on message could be problematic as the message can change.
You should look to refactor and define multiple exceptions or define codes for different scenarios.