junit testcase is pass , but still printing exception in console java - java

#Test
public void testGetAspectByAspectName() {
try {
this.getUserTwin();
assertEquals(userAlmService.getAspectByUserName("6cade-bced-4e69-8red-271c95d343baa", null).toString(),this.getAspect().toString());
}
catch (NullPointerException e) {
assertEquals(NullPointerException.class, e.getClass());
}
}
My intention this test case to check nullpointerexception. The Test case passed but I am getting NULL exception message in the console
how to restrict to do not print in console
I tried #Test(expected=NullPointerexception.class) still it is printing in console
java.lang.NullPointerException: null
I am using sprinrunner
#RunWith(SpringRunner.class)
#SpringBootTest

Try this:
#Rule
public ExpectedException exception = ExpectedException.none();
#Test
public void fooBar() throws FooBarException {
exception.expect(FooBarException.class);
exception.expectMessage(containsString("bla bla bla"));
//your code here
}

Related

Assert an Exception is Thrown in

I have this Junit test in my project
public class CalculatorBookingTest {
private CalculatorBooking calculatorBooking;
#Rule
public ExpectedException expectedException = ExpectedException.none();
#Before
public void setUp() {
calculatorBooking = new CalculatorBooking();
}
#Test
public void shouldThrowAnException_When_InputIsNull() {
calculatorBooking.calculate(null, null, 0, null);
expectedException.expect(CalculationEngineException.class);
expectedException.expectMessage("Error");
}
}
but when I run the test, the Exception is Thrown but nevertheless the test fail
You could do something like:
#Test(expected = CalculationEngineException.class)
public void shouldThrowAnException_When_InputIsNull() {
calculatorBooking.calculate(null, null, 0, null);
}
From Junit doc :
The Test annotation supports two optional parameters. The first,
expected, declares that a test method should throw an exception. If it
doesn't throw an exception or if it throws a different exception than
the one declared, the test fails.
You need to first tell JUnit that the method is expected to throw the exception. Then when it's thrown - it knows that the test passes. In your code you put expect() after the exception is thrown - so the execution doesn't even go that far. The right way:
#Test
public void shouldThrowAnException_When_InputIsNull() {
expectedException.expect(CalculationEngineException.class);
expectedException.expectMessage("Error");
calculatorBooking.calculate(null, null, 0, null);
}
Place expectedException.expect before the call that will throw the exception.
#Test
public void shouldThrowAnException_When_InputIsNull() {
expectedException.expect(CalculationEngineException.class);
expectedException.expectMessage("Error");
calculatorBooking.calculate(null, null, 0, null);
}

Unit test for thrown exception

I have a Spring Boot application where I have methods in my Service layer like:
public List<PlacementDTO> getPlacementById(final int id) throws MctException {
List<PlacementDTO> placementList;
try {
placementList = placementDao.getPlacementById(id);
} catch (SQLException ex) {
throw new MctException("Error retrieving placement data", ex);
}
return placementList;
}
What is the best way to unit test that MctException will be thrown? I tried:
#Test(expected = MctException.class)
public void testGetPlacementByIdFail() throws MctException, SQLException {
when(placementDao.getPlacementById(15)).thenThrow(MctException.class);
placementService.getPlacementById(15);
}
However, this doesn't test the right that an exception is actually thrown.
I think you have to stub the placementDao.getPlacementById(15) call to throw the SQLException instead of your MctException, like this:
#Test(expected = MctException.class)
public void testGetPlacementByIdFail() throws MctException, SQLException {
when(placementDao.getPlacementById(15)).thenThrow(SQLException.class);
placementService.getPlacementById(15);
}
This way when you call your Service method placementService.getPlacementById(15); you know that your MctException will encapsulate the SQLException and therefore your test could expect the MctException exception to be thrown.
You may want to try out the ExepctionException rule feature of Junit. This would allow greater granularity in verification of your exception handling in your unit test than the expected exception annotation.
#Rule
public ExpectedException thrown= ExpectedException.none();
#Test
public void testGetPlacementByIdFail(){
thrown.expect(MctException.class);
thrown.expectMessage("Error retrieving placement data");
//Test code that throws the exception
}
As the above snippet show, you would also be able to test on various properties of the exception like its message.

Why is caught Exception getting logged in the console while executing unit test with JUnit?

I am a newbie in JUnit and i am trying to write unit test for the following class:
class MyClass {
public void throwException() throws MyException {
try {
JSONObject json = new JSONObject();
json.getString("param");
} catch(JSONException e) {
throw new MyException(e);
}
}
}
My use case is such that i can only throw MyException (my wrapper around the Exception class) from the throwException() method. I have written a test case for this using JUnit as follows:
#Test(expected = MyException.class)
public void testIfThrowsException throws MyException {
MyClass myClass = new MyClass();
myClass.throwException();
}
When i run this unit test case, the test is passed but still JSONException is getting logged in the console. Console Message:
- param parameter is not string
org.json.JSONException: JSONObject["param"] not found.
at org.json.JSONObject.get(JSONObject.java:498)
at org.json.JSONObject.getString(JSONObject.java:669)
at .......
Is this the expected behavior or am i doing something wrong in the implementation of the unit test. If this is expected then how can i suppress such a console message.

Can junit test that a method will throw an exception?

Could you tell me please, is it normal practice to write a method (example: JUnit Test) that throws an Exception, for example:
class A {
public String f(int param) throws Exception {
if (param == 100500)
throw new Exception();
return "";
}
}
private A object = new A();
#Test
public void testSomething() throws Exception {
String expected = "";
assertEquals(object.f(5), expected);
}
In fact, method f() won't throw an exception for that parameter(5) but nevertheless I must declare that exception.
Yes it is completely fine, and if it does throw the exception the test will be considered as failed.
You need to specify that the method throws an Exception even if you know that the specific case does not (this check is done by the compiler).
In this case, what you expect is object.f(5) returns an empty string. Any other outcome (non-empty string or throwing an exception) would result in a failed test case.
A JUnit-Test is meant to test a given method for correct behavior. It is a perfectly valid scenario that the tested method throws an error (e.g. on wrong parameters). If it is a checked exception, you either have to add it to your test method declaration or catch it in the method and Assert to false (if the exception should not occur).
You can use the expected field in the #Test annotation, to tell JUnit that this test should pass if the exception occurs.
#Test(expected = Exception.class)
public void testSomething() throws Exception {
String expected = "";
assertEquals(object.f(5), expected);
}
In this case, the tested method should throw an exception, so the test will pass. If you remove the expected = Exception.class from the annotation, the test will fail if an exception occurs.
If the method you're calling throws a checked exception yes, you'll either need a try catch or to rethrow. It's fine to do this from the test itself. There are a variety of ways to test Exception using JUnit. I've tried to provide a brief summary below:
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
/**
* Example uses Kent Beck - Test Driven Development style test naming
* conventions
*/
public class StackOverflowExample {
#Rule
public ExpectedException expectedException = ExpectedException.none();
#Test
// Note the checked exception makes us re-throw or try / catch (we're
// re-throwing in this case)
public void calling_a_method_which_throws_a_checked_exception_which_wont_be_thrown() throws Exception {
throwCheckedException(false);
}
/*
* Put the class of the specific Exception you're looking to trigger in the
* annotation below. Note the test would fail if it weren't for the expected
* annotation.
*/
#Test(expected = Exception.class)
public void calling_a_method_which_throws_a_checked_exception_which_will_be_thrown_and_asserting_the_type()
throws Exception {
throwCheckedException(true);
}
/*
* Using ExpectedException we can also test for the message. This is my
* preferred method.
*/
#Test
public void calling_a_method_which_throws_a_checked_exception_which_will_be_thrown_and_asserting_the_type_and_message()
throws Exception {
expectedException.expect(Exception.class);
expectedException.expectMessage("Stack overflow example: checkedExceptionThrower");
throwCheckedException(true);
}
// Note we don't need to rethrow, or try / catch as the Exception is
// unchecked.
#Test
public void calling_a_method_which_throws_an_unchecked_exception() {
expectedException.expect(Exception.class);
expectedException.expectMessage("Stack overflow example: uncheckedExceptionThrower");
throwUncheckedException();
}
private void throwCheckedException(boolean willThrow) throws Exception {
// Exception is a checked Exception
if (willThrow) {
throw new Exception("Stack overflow example: checkedExceptionThrower");
}
}
private void throwUncheckedException() throws NullPointerException {
// NullPointerException is an unchecked Exception
throw new NullPointerException("Stack overflow example: uncheckedExceptionThrower");
}
}
You can test that the exception is launched with this:
#Test(expected = ValidationException.class)
public void testGreaterEqual() throws ValidationException {
Validate.greaterEqual(new Float(-5), 0f, "error7");
}

Mockito not recognizing my mocked class when passing through when()

I want the closeSession() method to throw an Exception when it is called so that I can test to see my logging is being done. I have mocked the Crypto object as mockCrypto and set it up as follows:
#Test
public void testdecrpyMcpDataExceptions() throws Exception {
Crypto mockCrypto = Mockito.mock(Crypto.class);
try {
mockCrypto = CryptoManager.getCrypto();
logger.info("Cyrpto Initialized");
} finally {
logger.info("Finally");
try {
logger.info("About to close Crypto!");
Mockito.doThrow(new CryptoException("")).when(mockCrypto).closeSession();
mockCrypto.closeSession();
} catch (CryptoException e) {
logger.warn("CryptoException occurred when closing crypto session at decryptMcpData() in CipherUtil : esi");
}
}
}
However when I run it I get the error :
Argument passed to when() is not a mock!
Am I mocking the class wrong or am I just missing something?
don't you overwrite your mock at
mockCrypto = CryptoManager.getCrypto();
Tested
#Test(expected=RuntimeException.class)
public void testdecrpyMcpDataExceptions() throws Exception {
Crypto mockCrypto = mock(Crypto.class);
doThrow(new RuntimeException()).when(mockCrypto).closeSession();
mockCrypto.closeSession();
}
works fine.
this line is overwriting your mock:
mockCrypto = CryptoManager.getCrypto();
and thats why it fails.

Categories