Junit testing forcing exception - exception

I have the following method:
public Object method(){
try
{
privatevoidmethod1();
privatevoidmethod2();
}
catch(Exception e)
{
Log.debug(e);
}
return object;
}
How do I force the exception so I can test the debug call?

Leaving aside how you'd test the debug call, you'd normally trigger an exception by providing suitable inputs such that an exception would be created/thrown. If that's not suitable, the alternative is to provide a substitute (mocked) component that has been configured/written to throw an exception e.g.
public MyClass(MyInjectedComponent component) {
this.component = component;
}
and you'd provide for your test an implementation of MyInjectedComponent that will throw an exception (for testing purposes). The approach of injecting components into other components is called dependency injection and worth investigating.
I'd normally use a mocking framework for this (e.g. Mockito or similar). However a trivial implementation of the above could be:
public class MyImplementationForTesting extends MyInjectedComponent {
public void method() throws Exception {
throw new Exception();
}
}

Related

EJB wraps my customExceptions throwed from interceptors

I'm studying interceptors and decorator and when experimenting with it I've encountered the problem that if I throw a checked exception from an interceptor, the EJBContainer wraps it as an EJBException, instead what I would like to show to the client is my custom exception.
Assume that I've one simple method and one interceptor that check if the parameters are valid like so:
#Interceptor
public class TestIntercepor {
#AroundInvoke
public Object test(InvocationContext invCtx) throws Exception{
try {
//check parameters...
return invCtx.proceed();
} catch (CustomException ex) {
throw new CustomException();
} catch (Exception ex) {
throw new Exception();
}
}
}
The exception that I want to throw if something's off is CustomException:
public class CustomException extends Exception {
public CustomException() {
super("ERROR! Input fields not valid");
}
}
now I've noticed in my SOAP Fault message that the exception throwed is an EJBException. I did some research and found out that the EJB Container wraps all the SystemException throwed, so I'm assuming that my CustomException throwed by the interceptor is treated as an uncecked exception for some reason, while if I throw the same exception from the business method, the client see exactly the right exception in the message.
I've even tryed to add the #ApplicationException annotation in my CustomException class for be completely sure that my Exception has to be treated as an ApplicationException instead of a SystemException, but it doesn't seem to be working.
There's something I'm missing?
I've found out that if your custom exception extends RuntimeException instead of Exception it works. Seems like that the #ApplicationException work only if the exception is a System Exception like RuntimeException and not if extends normal Exception.
#ApplicationException(rollback = true)
public class CustomException extends RuntimeException {
public CustomException() {
super("ERROR! Input fields not valid");
}
}

How do you test exceptions using mockito in RCP Application?

I have the following code in my performFinish() method of my Wizard Class :
public boolean performFinish() {
try {
getContainer().run(true, false, changeArtifactRunnable());
}
catch (InvocationTargetException | InterruptedException e) {
LoggerClass.logException(e);
}
I want to test Exception for InvocationTargetException and InterruptedException using Mockito.
In the above code, getContainer() method is from org.eclipse.jface.wizard.Wizard class and
public void run(boolean fork, boolean cancelable,
IRunnableWithProgress runnable) throws InvocationTargetException,
InterruptedException;
method is from org.eclipse.jface.operation.IRunnableContext class.
How do I test both the exceptions in performFinish() method?
You can use the expected keyword in order to do so. For example:
#Test(expected = InvocationTargetException.class)
public void testInvocationTargetException() {
\\Invoke the method to be tested under the conditions, such that InvocationTargetException is thrown by it. No need of any assert statements
}
===========================================================================
Edit:
#RunWith(MockitoJUnitRunner.class)
public class EditArtifactWizardTest {
#Spy
//use correct constructor of EditArtifactWizard
private EditArtifactWizard editArtifactWizardSpy=Mockito.spy(new EditArtifactWizard ());
#Test(expected = InvocationTargetException.class)
public void testInvocationTargetException() {
\\Invoke the method to be tested under the conditions, such that InvocationTargetException is thrown by it. No need of any assert statements
Mockito.when(editArtifactWizardSpy.getContainer()).thenThrow(InvocationTargetException.class);
editArtifactWizardSpy.performFinish();
}
}
You can create the Spy of EditArtifactWizard class and mock the behavior of the getContainerMethod.
P.S: Please excuse for typos or compilation error as I am not using any editor.

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
}
}

What's the meaning of Proctectable interface in JUnit source code?

I'm recently digging into the source code of JUnit-4.11, what confuse me is that the seemingly redundant Protectable interface. the declaration is as follows:
public interface Protectable {
public abstract void protect() throws Throwable;
}
In the TestResult class, there is a void run(final TestCase test) method, in which a anonymous Protectable instance is realized as follows:
protected void run(final TestCase test) {
startTest(test);
Protectable p = new Protectable() {
public void protect() throws Throwable {
test.runBare();
}
};
runProtected(test, p);
endTest(test);
}
runProtected method is as follows:
public void runProtected(final Test test, Protectable p) {
try {
p.protect();
} catch (AssertionFailedError e) {
addFailure(test, e);
} catch (ThreadDeath e) { // don't catch ThreadDeath by accident
throw e;
} catch (Throwable e) {
addError(test, e);
}
}
As we can see, what runProtected does is just executing test.runBare();, so is there any sense to the existence of Protectable interface? Why can't we just write code like below.
protected void run(final TestCase test) {
startTest(test);
test.runBare();
endTest(test);
}
To answer your final question first, you can't use
protected void run(final TestCase test) {
startTest(test);
test.runBare();
endTest(test);
}
because it won't do what you want. JUnit manages asserts using exceptions, specifically AssertionFailedError. So, Assert.assertEquals() throws an AssertionFailedError when the two values aren't equal. So, in the above method, the endTest(test) won't get called if there is an assertion failure, which means the correct events (failure/error of the test) won't get fired, and tearDown() won't get executed.
The Protectable interface is there to give a more generic interface to the runner, so that you don't have to hand a TestCase to the method, to allow different actions.
As an aside, this is part of the package junit.framework.*, which is JUnit 3. JUnit 4 is where it's at, and if you want to learn, look more in the org.junit.* packages.
It seems to handle thrown exceptions in specific way :
Call addFailure for assertion exception (your test failed), addError for other exception (your test is not well coded)
This interface is to protect the TestCase by adding Throwable.
so junit could run any testcase safely.
The Throwable class is the superclass of all errors and exceptions in the Java language.

JMS MessageCreator.createMessage() in Grails

I am trying to implement jms to my grails application.
I have several JMS consumer in a spring based enviroment listining
on an ActiveMQ broker. I wrote a simple test commandline client which creates
messages and receives them in an request response manner.
Here is the snippet that sends a MapMessage in Spring JMS way.
This works for me as long I am in my spring world.
final String corrID = UUID.randomUUID().toString();
asyncJmsTemplate.send("test.RequestQ", new MessageCreator()
{
public Message createMessage(Session session) throws JMSException {
try {
MapMessage msg = session.createMapMessage();
msg.setStringProperty("json", mapper.writeValueAsString(List<of some objects>));
msg.setJMSCorrelationID(corrID);
msg.setJMSReplyTo(session.createQueue("test.ReplyQ"));
return msg;
} catch (JsonGenerationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
});
BUT when I tried to implement this methods to my grails test app
I receive some METHOD_DEF exceptions. Sending simple TextMessages
via the jmsTemplate.convertAndSende(Queue, Message) provided by
the JMS Plugin works.
Can any one help me? Is this a common problem?
Cheers Hans
Not actually trying this out, I have to believe this is a syntax problem. What you're really doing with that anonymous class is passing a closure containing all the MessageCreator code into the constructor for the MessageCreator class. In Groovy, closures can be passed as the last argument to a function merely by placing it after the function name or the parenthesized first arguments.
SomeFunction( arg1, arg2) { some code }
is the same as
SomeFunction( arg1, arg2, { some code } )
What you really want is to convert the closure into an anonymous instance of a MessageCreator, which I believe you can accomplish by:
asyncJmsTemplate.send("test.RequestQ",
{ code in the anonymous block } as MessageCreator );
I found this on StackOverflow, actually, though it's a poorly created question. Read all the responses, and you should see something relevant: Best groovy closure idiom replacing java inner classes?
I have had the same problems and here is my working solution:
I have created a new class MyMessageCreator in the src folder which implements the origin JMS MessageCreator interface.
With this I can create a new MyMessageCreator object and can call the createMessage(Session session) function to generate a new message.
To get the session object I use the jmsTemplate.
public class MyMessageCreator implements MessageCreator {
#Override
public Message createMessage(Session session) throws JMSException {
return session.createMapMessage();
}
}
Here is the relevant groovy code:
Session session = jmsTemplate.getConnectionFactory().createConnection().createSession(false, Session.AUTO_ACKNOWLEDGE)
MapMessage msg = new MyMessageCreator().createMessage(session);
Hope this helps,
Mirko