Using #Test and expected - junit

in my Junit tests I have a test case that must be fail only when IOexception is throwing by my object under test.
So ,if my object under test throw IllegalStateException (or other Error or Exception) my test case is OK but if my object under test throw IOexception my test case must be fail.
How can I do it ?
Thanks for all.

You can use the expected exception rule
#Rule
public ExpectedException expected = new ExpectedException();
#Test
public void doSomethingWithNoIOException() {
// we expect an exception that's NOT an instance of IOException
// you'll need to static import the hamcrest matchers referenced below
expected.expect(not(instanceOf(IOException.class));
// call the method under test
callSomething();
}

As you want to fail when exception is NOT an IOException, You can do that by catching the IOException and asserting with fail() like below:
#Test
public void yourTestScenario() {
try {
//code that throws IOException and other Exceptions
} catch(IOException ioexe) {
Assert.fail();
} catch(Exception exe) {
//Ignore
}
}

Related

How to mock a void private method to throw Abstract Exception with Powermock?

While writing unit test case for method someMethod1, I have a use case where I'm trying to ensure that an abstract exception (AnalysisException) is thrown when method (someMethod2) is called. Class under test is JdbcTemplateSampleImpl .
public class JdbcTemplateSampleImpl {
public void someMethod1() {
someMethod2();
}
private void someMethod2() throws AnalysisException {
// some code here
}
}
I am using PowerMockito to do like this
#Test(expected = com.test.AnalysisException.class)
public void abstractClassExceptionCheck2Test1() throws Throwable {
JdbcTemplateSampleImpl jdbcTemplateSampleImpl1 =
PowerMockito.spy(jdbcTemplateSampleImpl0);
PowerMockito.doThrow(mock(AnalysisException.class)).
when(jdbcTemplateSampleImpl1,"classCheck2");
jdbcTemplateSampleImpl1.abstractClassExceptionCheck2();
}
But while executing test case , i'm getting an error like this
java.lang.Exception: Unexpected exception, expected "com.test.AnalysisException" but was "java.lang.NullPointerException"
Mock the exception outside of the doThrow method call.
AnalysisException e = mock(AnalysisException.class);
PowerMockito.doThrow(e).
when(jdbcTemplateSampleImpl1,"classCheck2");

Asserting Exceptions for private method in JUnit

private static String getToken(HttpClient clientInstance) throws badcredentailsexception{
try{
// some process here throws IOException
}
catch(IOexception e){
throw new badcredentailsexception(message, e)
}
}
Now I need to write Junit test for the above method, My Junit code for above function is below
#Test(expected = badcredentailsexception.class)
public void testGetTokenForExceptions() throws ClientProtocolException, IOException, NoSuchMethodException, SecurityException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
Mockito.when(mockHttpClient.execute(Mockito.any(HttpPost.class))).thenThrow(IOException.class);
// mocked mockHttpClient to throw IOException
final Method method = Client.class.getDeclaredMethod("getToken", HttpClient.class);
method.setAccessible(true);
Object actual = method.invoke(null, mockHttpClient);
}
But this test is not being passed, any improvements??
Can we check the exception thrown by private method from junit ??
First of all, it is an antipattern to test a private method. It is not part of your API. See the already linked question: Testing Private method using mockito
To answer your question: When invoking a method via Reflection and the invoked method throws an Exception, the Reflection API wraps the Exception into an InvocationTargetException. So you could catch the InvocationTargetException and inspect the cause.
#Test
public void testGetTokenForExceptions() throws Exception {
HttpClient mockHttpClient = mock(HttpClient.class);
when(mockHttpClient.execute(any(HttpPost.class))).thenThrow(IOException.class);
Method method = Client.class.getDeclaredMethod("getToken", HttpClient.class);
method.setAccessible(true);
try {
method.invoke(null, mockHttpClient);
fail("should have thrown an exception");
} catch (InvocationTargetException e) {
assertThat(e.getCause(), instanceOf(BadCredentialsException.class));
}
}
You couldn't test private methods with JUnit or even with Mockito framework.
You could find more details in this question: Testing Private method using mockito
If you really need to test this private method, you should use PowerMock framework.

Junit test for Exception

I try to test my Exception JUnit and the test doesn't pass I have this error trace :
org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnitAndHigherRunnerImpl.java:37)
and
org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
and here is my code :
PatientEntityFacade pef = new PatientEntityFacade();
Mockito.when(pef.findByNumber(5555)).thenReturn(patientEntity);
#Rule
public ExpectedException thrown = ExpectedException.none();
#Test
public void shouldThrow() throws PatientNotFoundException
{
thrown.expect(PatientNotFoundException.class);
thrown.expectMessage("personalized exception no patient found");
try {
pef.findByNumber(5555);
} catch (com.patient.facade.PatientNotFoundException e) {
e.printStackTrace();
}
}
If you watn to test your Exception, then do it the right way.
Define when Exception should be thrown.
in #BeforeClass if every Method should
in #Test-method if only this Method should throw it.
Notice, that you can use any(X.class) if other methods got other values for it.
DonĀ“t try-catch in unit-tests.
Catch it this way and if there is no Exception, the test will fail.
#Test(expected = PatientNotFoundException.class)
public void shouldThrow()
pef.findByNumber(5555);
}

Exception handling - Try Catch ambiguous behaviour (??)

This is My code
from("direct:test-POST")
.doTry()
.process(new Processor() {
#Override
public void process(Exchange arg0) throws Exception {
throw new NullPointerException(" Null value");
}
})
.doCatch(NullPointerException.class)
.log("${exception}") // This Prints NullPointer Exception
.process(new Processor() {
#Override
public void process(Exchange arg0) throws Exception {
System.out.println( arg0.getException() ); //This prints Null
}
})
.end();
Am using jetty:run to run this camel route.
How do I catch the exception. It prints the exception correct in log. but inside the processor, the exception is null. what am I missing
I would think the exception is found on a property on the exchange. Something like:
Throwable caused = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, NullPointerException.class);
assertNotNull(caused);

test "handled exceptions" junit

I have a method with a handled exception:
public boolean exampleMethod(){
try{
Integer temp=null;
temp.equals(null);
return
}catch(Exception e){
e.printStackTrace();
}
}
I want to test it
public void test_exampleMethod(){}
I have tried
#Rule
public ExpectedException expectedException=ExpectedException.none();
public void test_exampleMethod(){
expectedException.expect(JsonParseException.class);
exampleMethod();
}
but that doesnt work because the exception is handled inside.
I also tried
#Test(expected=JsonParseException.class)
but same issue...the exception is handled
I know that I can just do
assertTrue(if(exampleMethod()))
but it will still print the stack trace to the log. I would prefer clean logs...Any suggestions?
You cannot test what a method is doing internally. This is completely hidden (unless there are side effects, that are visible outside).
The test can check that for a specific input the method returns a expected output. But you can not check, how this is done. So you have no way to detect if there was a exception that you have handled.
So: either don't handle the exception (let the test catch the exception), or return a special value that tells you about the exception.
Anyway, I hope your real exception handling is more sensible than in your example.
If the method does not throw an exception you cannot expect to get one!
Below an example how write a Junit Test for a method that throws an Exception:
class Parser {
public void parseValue(String number) {
return Integer.parseInt(number);
}
}
Normal test case
public void testParseValueOK() {
Parser parser = new Parser();
assertTrue(23, parser.parseValue("23"));
}
Test case for exception
public void testParseValueException() {
Parser parser = new Parser();
try {
int value = parser.parseValue("notANumber");
fail("Expected a NumberFormatException");
} catch (NumberFormatException ex) {
// as expected got exception
}
}