I'm a beginner of AssertJ. I encountered some issue when I use AssertJ to do Unit Testing.
JAVA: version 8
AssertJ: 3.11.1
I have a source code as below, to capture an exception and throw another exception.
try {
Integer.valueOf(valueA);
} catch(Exception e) {
throw new XXXException("value is not valid", e);
}
My test case as below failed, and I was told wrong exception assert, it's a bit confusing.
Throwable thrown = catchThrowable(() -> {
contract.init(ctx, "A", "100A", "B", "200");
});
assertThat(thrown).isInstanceOf(XXXException.class);
The error message as below, it seems like the original exception was captured by AssertJ. Anyone can help? Is it a bug or my mistake of AssertJ API usage? Many Thanks.
java.lang.AssertionError:
Expecting:
<java.util.IllegalFormatConversionException: d != java.lang.String>
to be an instance of:
<xxxx.XXXException>
but was:
<"java.util.IllegalFormatConversionException: d != java.lang.String
Here's my attempt to reproduce the issue, the test passes as expected:
#Test
public void test() {
Throwable thrown = catchThrowable(() -> f());
assertThat(thrown).isInstanceOf(RuntimeException.class);
}
private void f() {
try {
Integer.valueOf("100A");
} catch (Exception e) {
throw new RuntimeException("value is not valid", e);
}
}
Can you show us what contract.init is doing?
Another possibility would be in the stack trace, if it contains a %d somewhere stack trace it might be interpreted by a String.format but hard to say without more details.
Related
"Only the types that are inherited from the Throwable class can be thrown".
Could anybody explain me. Why not every type are throwable? If in doc there no mention about function can throw exception, it's mean that it do not have exception?
For example I thought that next try-catch block would work. But it is not.
try
{
writeln("(((((((((");
latestdtonpage = dts.sort!((a,b) => a>b).front; //latest date-time. from page.
}
catch(Exception e)
{
writeln("Can't select the latest Date from parsed date");
writeln(e);
}
But output in case of exception is next (no exception text):
(((((((((
core.exception.AssertError#C:\D\dmd2\windows\bin\..\..\src\phobos\std\array.d(73
9): Attempting to fetch the front of an empty array of DateTime
----------------
0x0051C4C9 in _d_assert_msg
0x00468E78 in pure nothrow ref #property #nogc #safe std.datetime.DateTime std.r
ange.__T11SortedRangeTAS3std8datetime8DateTimeS473app19StackOverflowParser5parse
MFAyaZ9__lambda2Z.SortedRange.front() at C:\D\dmd2\windows\bin\..\..\src\phobos\
std\range.d(8418)
0x0044F908 in void app.StackOverflowParser.parse(immutable(char)[]) at D:\code\T
rendoMetr\source\app.d(173)
0x0044F700 in app.StackOverflowParser app.StackOverflowParser.__ctor(app.DBConne
ct) at D:\code\TrendoMetr\source\app.d(150)
0x0044F199 in _Dmain at D:\code\TrendoMetr\source\app.d(33)
0x0052EDCA in D2rt6dmain211_d_run_mainUiPPaPUAAaZiZ6runAllMFZ9__lambda1MFZv
0x0052ED9F in void rt.dmain2._d_run_main(int, char**, extern (C) int function(ch
ar[][])*).runAll()
0x0052ECB5 in _d_run_main
0x00470198 in main
0x005667D1 in mainCRTStartup
0x76D1336A in BaseThreadInitThunk
0x772A9F72 in RtlInitializeExceptionChain
0x772A9F45 in RtlInitializeExceptionChain
Error executing command run: Program exited with code 1
How I can throw exception in this code?
Your code throws an AssertError, indicating that dts.sort!((a,b) => a>b) is empty, and you shouldn't call .front on it. Instead, query .empty first, and act accordingly when it's true.
AssertError inherits from Error which in turn inherits from Throwable but not from Exception. So catch(Exception e) doesn't catch it. And you should not catch Errors anyway, as they indicate that the program is in an unrecoverable error-state.
AssertError in particular signals a logic bug in your program. Here: calling .front on an empty range. Don't catch AssertError, but fix your code instead.
I have a method that throws exception. And i have a test like this.
#Rule
public ExpectedException expectedEx = ExpectedException.none();
#Test
public void shouldThrowExceptionIfValidationFails() throws Exception {
doThrow(new InvalidException("Invalid Token")).when(obj).foo(any());
expectedEx.expect(InvalidException.class);
expectedEx.expectMessage("Invalid Token");
// my method call
// verify DB save doesn't happens
assertTrue(false);
}
The test assert for exception, and since the exception is thrown the test passes. It doesn't care about the last line assertTrue(false)
How can i make sure that my other assertions are also satisfied.
This is the pattern I follow for this case. It uses ExpectedException as designed. I like the throw e rather than failing after method method call in the try because it will not result in a false-positive if someone decides to delete the fail (which people have a tendency to do when they see fail() or if a test is failing because it hits a fail()).
#Test
public void shouldThrowExceptionIfValidationFails() throws Exception {
doThrow(new InvalidException("Invalid Token")).when(obj).foo(any());
expectedEx.expect(InvalidException.class);
expectedEx.expectMessage("Invalid Token");
try{
// my method call
}catch(InvalidException e){
// verify DB save doesn't happens
assertTrue(false);
throw e;
}
}
Can I test whether a particular Exception is not thrown?
The other way round is easy using #Test[expect=MyException].
But how can I negate this?
If you want to test if a particular Exception is not thrown in a condition where other exceptions could be thrown, try this:
try {
myMethod();
}
catch (ExceptionNotToThrow entt){
fail("WHOOPS! Threw ExceptionNotToThrow" + entt.toString);
}
catch (Throwable t){
//do nothing since other exceptions are OK
}
assertTrue(somethingElse);
//done!
You can do the following using assertj
if you want to check if exception is not thrown then
Throwable throwable = catchThrowable(() -> sut.method());
assertThat(throwable).isNull();
or you expect to throw
Throwable throwable = catchThrowable(() -> sut.method());
assertThat(throwable).isInstanceOf(ClassOfExecption.class)
.hasMessageContaining("expected message");
catch-exception makes the example of Freiheit a bit more concise:
catchException(a).myMethod();
assertFalse(caughtException() instanceof ExceptionNotToThrow);
Another latest solution could be using Junit5 assertDoesNotThrow:
assertDoesNotThrow( () -> myMethod() , "MyException is not thrown")
Use #Test(expected = Test.None::class) (in Kotlin)
I am trying to deal with these exception. For example when a user, loads an invalid XML file, then SAXParseException is thrown and he is asked to load another file.
it seems that "catch" won't work here.
here's my code:
public void parseXML_FROM_file (File xml_file)
{
try {
JAXBContext jc = JAXBContext.newInstance ("generated");
//Creating an Unmarshaller.
Unmarshaller u = jc.createUnmarshaller ();
//USING FILE APPROACH
System.out.println("Using FILE approach:");
JAXBElement element = (JAXBElement) u.unmarshal(xml_file);
TEST_Class mainTest = (TEST_Class) element.getValue ();
} catch (JAXBException e)
{
e.printStackTrace ();
}catch (SAXParseException e)
//do something
}catch (UnmarshalException e)
//do something
}
}
even, this wont work
catch (JAXBException,SAXParseException,UnmarshalException e)
{
//do something
}
#don robi
this is what i get:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The type JAXBException is not generic; it cannot be parameterized with arguments <SAXParseException, UnmarshalException>
Syntax error on token ",", < expected
Syntax error, insert ">" to complete ReferenceType1
at XML_Parser.parseXML_FROM_file(XML_Parser.java:64)
at Main_Class.main(Main_Class.java:13)
The exception indicates that this is a compilation exception. Once the errors are fixed in your XML_parser class you should get the JAXB behaviour you are expecting.
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The type JAXBException is not generic; it cannot be parameterized with arguments <SAXParseException, UnmarshalException>
Syntax error on token ",", < expected
Syntax error, insert ">" to complete ReferenceType1
at XML_Parser.parseXML_FROM_file(XML_Parser.java:64)
at Main_Class.main(Main_Class.java:13)
I'm using ScalaTest for testing some Scala code.
I currently testing for expected exceptions with code like this
import org.scalatest._
import org.scalatest.matchers.ShouldMatchers
class ImageComparisonTest extends FeatureSpec with ShouldMatchers{
feature("A test can throw an exception") {
scenario("when an exception is throw this is expected"){
evaluating { throw new Exception("message") } should produce [Exception]
}
}
}
But I would like to add additional check on the exception, e.g. I would like to check that the exceptions message contains a certain String.
Is there a 'clean' way to do this? Or do I have to use a try catch block?
I found a solution
val exception = intercept[SomeException]{ ... code that throws SomeException ... }
// you can add more assertions based on exception here
You can do the same sort of thing with the evaluating ... should produce syntax, because like intercept, it returns the caught exception:
val exception =
evaluating { throw new Exception("message") } should produce [Exception]
Then inspect the exception.
If you need to further inspect an expected exception, you can capture it using this syntax:
val thrown = the [SomeException] thrownBy { /* Code that throws SomeException */ }
This expression returns the caught exception so that you can inspect it further:
thrown.getMessage should equal ("Some message")
you can also capture and inspect an expected exception in one statement, like this:
the [SomeException] thrownBy {
// Code that throws SomeException
} should have message "Some message"