简体   繁体   English

如何编写用于数据库调用的JUnit单元测试?

[英]How to write a JUnit unit test for database call?

For example, if I have something like this: 例如,如果我有这样的事情:

try {
 // db call
} catch ( Exception e ) {
 return false
}

I want to write a unit test to test this method. 我想编写一个单元测试来测试此方法。 How should I write that? 我该怎么写? Or to say it differently, what will be an example of code that will cause SQLException or any other exception to be thrown? 或者换句话说,将导致引发SQLException或任何其他异常的代码示例是什么?

We usually write such a test code like this: 我们通常编写这样的测试代码:

try {
    // Do something you expect to fail.
    Assert.fail();
} catch (SQLException e) { // Expected exception type.
    Assert.assertEquals(e.getMessage(), "Expected message");
    // Or alternatively.
    Assert.assertTrue(e.getMessage().startsWith("Expected start of the message"));
}

The Assert.fail() part makes sure that the test fails in case the code did not throw the error. Assert.fail()部分确保在代码未引发错误的情况下测试失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM