Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can simply use the @Test Annotation</p> <p>@Test(expected=RuntimeException.class)</p> <p>The other solution is, when you expect an exception, you should let fail your test </p> <pre><code>@Test public void testConnectionFailure() { ... try { dbConnector.connectionInit(); fail("an exception should be thrown...") } catch (Exception e) { assertTrue(e instanceof SQLException); } ... } </code></pre> <p><strong>Update #1:</strong></p> <p>I think your code and the testcase is not very well, because in your code you're catching all "good" exceptions! But they are telling you whats went wrong.</p> <p>So let your code throw these exceptions. </p> <p>But the other side is: Why you are writing a test case for standard <em>java</em> or <em>java.sql</em> features (ClassLoading, DriverManager)? </p> <p><strong>Update #2:</strong></p> <p>I will explain it by your example, because I am not an english native. ;)</p> <p>Your Code:</p> <pre><code>try { Class.forName(dbObject.getDriver()); } catch (Exception e) { Logger lgr = Logger.getLogger(PostgreLocationManager.class.getName()); lgr.log(Level.SEVERE, e.getMessage(), e); } </code></pre> <p>Your Code in words:</p> <pre><code>try { Do something from java standard. //Class.forName(dbObject.getDriver()); } if an exception occures, go in this block //catch (Exception e) { Just print out the exception. If someone knowns about your application he'll take a look in the log. If not, your exception is lost, after leaving this block. And I think here is your problem! Do not catch any exceptions in a so low level of your application. } </code></pre> <p>Your Testcase: </p> <pre><code>@Test public void testDriverFailure() { .... try { dbConnector.connectionInit(); } catch (Exception e) { assertTrue(e instanceof ClassNotFoundException); } } </code></pre> <p>Your Testcase in words: </p> <pre><code>@Test public void testDriverFailure() { .... try { try to init your dbConnector. } Catch exceptions ( They never thrown, because you already catched them in the method connectionInit(). And here right now, you know, why its a bad idea to catch exceptions and place them into logfiles (except in the very high level of your application)! ) { Now Check, that the Java-VM ClassLoader (Not your code!!!) will throw an ClassNotFoundException. Why you not trusting the jvm developers? ;) } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload