Created
March 18, 2016 00:24
-
-
Save djangofan/3cbfe889bef0c9547b68 to your computer and use it in GitHub Desktop.
Class to create a Throwable in Java for testing expected exceptions from a mock framework.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.healthsparq.qa.framework.util; | |
import java.lang.reflect.Constructor; | |
import java.lang.reflect.Method; | |
/** | |
* Use this to create a new Exception for a unit test. | |
*/ | |
public class CreateThrowable | |
{ | |
private static boolean causesAllowed = true; | |
/** | |
* Create a new RuntimeException, setting the cause if possible. | |
* | |
* @param message | |
* @param cause | |
* @return A runtime exception object. | |
*/ | |
public static RuntimeException createRuntimeException(String message, Throwable cause) | |
{ | |
return (RuntimeException) createWithCause( | |
RuntimeException.class, message, cause); | |
} | |
/** | |
* Create a new Exception, setting the cause if possible. | |
* | |
* @param clazz | |
* @param message | |
* @param cause | |
* @return A Throwable. | |
*/ | |
public static Throwable createWithCause(Class clazz, String message, Throwable cause) | |
{ | |
Throwable re = null; | |
if (causesAllowed) | |
{ | |
try | |
{ | |
Constructor constructor = clazz | |
.getConstructor(new Class[]{String.class, | |
Throwable.class}); | |
re = (Throwable) constructor | |
.newInstance(new Object[]{message, cause}); | |
} | |
catch (RuntimeException e) | |
{ | |
throw e; | |
} | |
catch (Exception e) | |
{ | |
causesAllowed = false; | |
} | |
} | |
if (re == null) | |
{ | |
try | |
{ | |
Constructor constructor = clazz.getConstructor(new Class[]{String.class}); | |
re = (Throwable) constructor.newInstance(new Object[]{message + " caused by " + cause}); | |
} | |
catch (RuntimeException e) | |
{ | |
throw e; | |
} | |
catch (Exception e) | |
{ | |
throw new RuntimeException("Error caused " + e); // should be impossible | |
} | |
} | |
return re; | |
} | |
/** | |
* Set the cause of the Exception. Will detect if this is not allowed. | |
* | |
* @param onObject | |
* @param cause | |
*/ | |
public static void setCause(Throwable onObject, Throwable cause) | |
{ | |
if (causesAllowed) | |
{ | |
try | |
{ | |
Method method = onObject.getClass().getMethod("initCause", new Class[]{Throwable.class}); | |
method.invoke(onObject, new Object[]{cause}); | |
} | |
catch (RuntimeException e) | |
{ | |
throw e; | |
} | |
catch (Exception e) | |
{ | |
causesAllowed = false; | |
} | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment