Groovy wraps a java exception in its own runtime.InvokerInvocationException
I'm using groovy to write unit tests for my开发者_C百科 java project (I'd advise all to try it out) One of my unit tests is testing that the tested code (in java) catches an exception of a specific type and rethrows an app exception:
java code (under test):
try
{
dao.save(obj)
}
catch(DataIntegrityException dupex)
{
....
throw new AppException("duplicate name");
}
The groovy test code mocks(proxies) the dao call using groovy's map of closures
[ save:
{ obj->
...
throw new DataIntegrityException("duplicate"); //DataIntegrityException is a runtime exception (unchecked)
}
] as DAO;
Pretty straightforward. However, when executing the test class, the actual exception thrown is groovy's runtime.Invoker.InvocationException which wraps the DataIntegrity exception. Obviously, the java code knows nothing about groovy and its exceptions, so the catch block is not executed. I'm using Netbeans 7 to actually execute the test and it just uses groovyc to compile the groovy file into a java class, and so it's just being executed as a normal JUnit test. Anyone know how to overcome this? couldn't find it listed in groovy's bugs, but sure seems like one.
Just using this for a little more space, not yet an answer. I can get the following (minimal) setup to work:
Dao.java
public interface Dao { void save(Object obj) throws DataIntegrityException; }
DataIntegrityException.java
public class DataIntegrityException extends RuntimeException {
public DataIntegrityException(String str) { super(str); }
}
Test.java
public class Test {
public void doIt(Dao dao) {
try {
dao.save(new Object());
} catch (DataIntegrityException e) {
System.out.println("Caught DataIntegrityException")
}
}
}
test_case.groovy
d = [save: { throw new DataIntegrityException('duplicate') }] as Dao
new Test().doIt(d)
This works, i.e., it prints "Caught DataIntegrityException" to the console, using Java 6 and Groovy 1.8 (which is what I have on my machine. At the very least, the issue must lie somewhere outside of the code you've posted here.
Personally, I'd think you'd need some step-through debugging. It seems likely that the exception is being thrown from elsewhere in the code (perhaps in whatever is contained in the ellipses in your version prior to throw new DataIntegrityException()
).
精彩评论