提交 89e4ea89 authored 作者: Thomas Mueller's avatar Thomas Mueller

Simplified test cases using AssertThrows(...).

上级 0dd2631a
......@@ -217,7 +217,7 @@ public abstract class TestBase {
*
* @return the directory, possibly including file system prefix
*/
protected String getBaseDir() {
public String getBaseDir() {
String dir = baseDir;
if (config != null) {
if (config.record) {
......
......@@ -321,15 +321,16 @@ public class TestCluster extends TestBase {
Server n2 = org.h2.tools.Server.createTcpServer("-tcpPort", "" + port2, "-baseDir", getBaseDir() + "/node2").start();
// try to connect in standalone mode - should fail
// should not be able to connect in standalone mode
try {
DriverManager.getConnection("jdbc:h2:tcp://localhost:"+port1+"/test", user, password);
fail("should not be able to connect in standalone mode");
getConnection("jdbc:h2:tcp://localhost:"+port1+"/test", user, password);
fail();
} catch (SQLException e) {
assertKnownException(e);
}
try {
DriverManager.getConnection("jdbc:h2:tcp://localhost:"+port2+"/test", user, password);
fail("should not be able to connect in standalone mode");
getConnection("jdbc:h2:tcp://localhost:"+port2+"/test", user, password);
fail();
} catch (SQLException e) {
assertKnownException(e);
}
......
......@@ -225,9 +225,7 @@ public class TestMemoryUsage extends TestBase {
prep.setInt(1, i);
ResultSet rs = prep.executeQuery();
rs.next();
if (rs.next()) {
fail("one row expected, got more");
}
assertFalse(rs.next());
if (i % 50000 == 0) {
trace(" " + (100 * i / len) + "%");
}
......@@ -242,9 +240,7 @@ public class TestMemoryUsage extends TestBase {
prep.setInt(1, random.nextInt(len));
ResultSet rs = prep.executeQuery();
rs.next();
if (rs.next()) {
fail("one row expected, got more");
}
assertFalse(rs.next());
if (i % 50000 == 0) {
trace(" " + (100 * i / len) + "%");
}
......
......@@ -310,9 +310,7 @@ public class TestPowerOff extends TestBase {
int state;
Database.setInitialPowerOffCount(0);
Connection conn = getConnection(url);
if (((JdbcConnection) conn).getPowerOffCount() != 0) {
fail("power off count is not 0");
}
assertEquals(0, ((JdbcConnection) conn).getPowerOffCount());
Statement stat = conn.createStatement();
DatabaseMetaData meta = conn.getMetaData();
ResultSet rs = meta.getTables(null, null, "TEST", null);
......
......@@ -73,8 +73,8 @@ public class TestSQLInjection extends TestBase {
reconnect("sqlInjection");
try {
assertTrue(checkPasswordInsecure("123456"));
fail("Should fail now");
checkPasswordInsecure("123456");
fail();
} catch (SQLException e) {
assertKnownException(e);
}
......
......@@ -381,9 +381,8 @@ public class TestTransaction extends TestBase {
result.add(table + "." + column);
}
}
if (result.size() != 4) {
fail("Wrong result, should be NEST1.ID, NEST1.NAME, NEST2.ID, NEST2.NAME but is " + result);
}
// should be NEST1.ID, NEST1.NAME, NEST2.ID, NEST2.NAME
assertEquals(result.toString(), 4, result.size());
result = New.arrayList();
test(stat, "INSERT INTO NEST1 VALUES(1,'A')");
test(stat, "INSERT INTO NEST1 VALUES(2,'B')");
......@@ -400,9 +399,8 @@ public class TestTransaction extends TestBase {
result.add(v1 + "/" + v2);
}
}
if (result.size() != 4) {
fail("Wrong result, should be A/1, A/2, B/1, B/2 but is " + result);
}
// should be A/1, A/2, B/1, B/2
assertEquals(result.toString(), 4, result.size());
result = New.arrayList();
rs1 = s1.executeQuery("SELECT * FROM NEST1 ORDER BY ID");
rs2 = s1.executeQuery("SELECT * FROM NEST2 ORDER BY ID");
......@@ -413,9 +411,8 @@ public class TestTransaction extends TestBase {
String v1 = rs2.getString("VALUE");
result.add(v1);
}
if (result.size() != 2) {
fail("Wrong result, should be A, B but is " + result);
}
// should be A, B
assertEquals(result.toString(), 2, result.size());
test(stat, "DROP TABLE NEST1");
test(stat, "DROP TABLE NEST2");
}
......@@ -424,9 +421,7 @@ public class TestTransaction extends TestBase {
ResultSet rs = stat.executeQuery(sql);
rs.next();
String s = rs.getString(1);
if (s == null ? (data != null) : (!s.equals(data))) {
fail("s= " + s + " should be: " + data);
}
assertEquals(data, s);
}
private void test(Statement stat, String sql) throws SQLException {
......
......@@ -185,9 +185,9 @@ public class TestViewAlterTable extends TestBase {
rs = conn.getMetaData().getTables(null, null, null, null);
while (rs.next()) {
if (!rs.getString(2).equals("INFORMATION_SCHEMA")) {
fail("Should have no tables left in the database, not: " + rs.getString(2) + "." + rs.getString(3));
}
// should have no tables left in the database
assertEquals(rs.getString(2) + "." + rs.getString(3),
"INFORMATION_SCHEMA", rs.getString(2));
}
}
......
......@@ -159,9 +159,9 @@ public class TestViewDropView extends TestBase {
ResultSet d = conn.getMetaData().getTables(null, null, null, null);
while (d.next()) {
if (!d.getString(2).equals("INFORMATION_SCHEMA")) {
fail("Should have no tables left in the database, not: " + d.getString(2) + "." + d.getString(3));
}
// should have no tables left in the database
assertEquals(d.getString(2) + "." + d.getString(3),
"INFORMATION_SCHEMA", d.getString(2));
}
}
}
......@@ -165,9 +165,7 @@ public class TestBatchUpdates extends TestBase {
conn = getConnection("batchUpdates");
stat = conn.createStatement();
DatabaseMetaData meta = conn.getMetaData();
if (!meta.supportsBatchUpdates()) {
fail("does not support BatchUpdates");
}
assertTrue(meta.supportsBatchUpdates());
stat.executeUpdate("CREATE TABLE TEST(KEY_ID INT PRIMARY KEY,"
+ "C_NAME VARCHAR(255),PRICE DECIMAL(20,2),TYPE_ID INT)");
String newName = null;
......@@ -231,11 +229,7 @@ public class TestBatchUpdates extends TestBase {
// System.out.println("upc="+p.executeUpdate());
trace("updateCount length:" + updateCountLen);
if (updateCountLen != 3) {
fail("updateCount: " + updateCountLen);
} else {
trace("addBatch add the SQL statements to Batch ");
}
assertEquals(3, updateCountLen);
String query1 = "SELECT COUNT(*) FROM TEST WHERE TYPE_ID=2";
String query2 = "SELECT COUNT(*) FROM TEST WHERE TYPE_ID=3";
String query3 = "SELECT COUNT(*) FROM TEST WHERE TYPE_ID=4";
......@@ -268,11 +262,7 @@ public class TestBatchUpdates extends TestBase {
int[] updateCount = stat.executeBatch();
updCountLength = updateCount.length;
trace("updateCount Length:" + updCountLength);
if (updCountLength != 3) {
fail("addBatch " + updCountLength);
} else {
trace("addBatch add the SQL statements to Batch ");
}
assertEquals(3, updCountLength);
String query1 = "SELECT COUNT(*) FROM TEST WHERE TYPE_ID=1";
ResultSet rs = stat.executeQuery(query1);
rs.next();
......@@ -285,9 +275,7 @@ public class TestBatchUpdates extends TestBase {
for (int j = 0; j < updateCount.length; j++) {
trace("Update Count:" + updateCount[j]);
trace("Returned Value : " + retValue[j]);
if (updateCount[j] != retValue[j]) {
fail("j=" + j + " right:" + retValue[j]);
}
assertEquals("j:" + j, retValue[j], updateCount[j]);
}
}
......@@ -303,18 +291,11 @@ public class TestBatchUpdates extends TestBase {
prep.setInt(1, 4);
prep.addBatch();
prep.clearBatch();
int[] updateCount = prep.executeBatch();
int updCountLength = updateCount.length;
if (updCountLength == 0) {
trace("clearBatch Method clears the current Batch ");
} else {
fail("clearBatch " + updCountLength);
}
assertEquals(0, prep.executeBatch().length);
}
private void testClearBatch02() throws SQLException {
trace("testClearBatch02");
int updCountLength = 0;
String sUpdCoffee = COFFEE_UPDATE1;
String sInsCoffee = COFFEE_INSERT1;
String sDelCoffee = COFFEE_DELETE1;
......@@ -322,14 +303,7 @@ public class TestBatchUpdates extends TestBase {
stat.addBatch(sDelCoffee);
stat.addBatch(sInsCoffee);
stat.clearBatch();
int[] updateCount = stat.executeBatch();
updCountLength = updateCount.length;
trace("updateCount Length:" + updCountLength);
if (updCountLength == 0) {
trace("clearBatch Method clears the current Batch ");
} else {
fail("clearBatch");
}
assertEquals(0, stat.executeBatch().length);
}
private void testExecuteBatch01() throws SQLException {
......@@ -563,7 +537,7 @@ public class TestBatchUpdates extends TestBase {
rs.close();
stat.close();
trace("Count val is: " + count);
// Make sure that we have the correct error code for
// make sure that we have the correct error code for
// the failed update.
if (!(batchUpdates[1] == -3 && count == 1)) {
fail("insert failed");
......
......@@ -763,13 +763,8 @@ public class TestPreparedStatement extends TestBase {
assertTrue(prep.execute());
rs = prep.getResultSet();
assertFalse(prep.getMoreResults());
try {
// supposed to be closed now
rs.next();
fail("getMoreResults didn't close this result set");
} catch (SQLException e) {
trace("no error - getMoreResults is supposed to close the result set");
}
// supposed to be closed now
assertThrows(ErrorCode.OBJECT_CLOSED, rs).next();
assertTrue(prep.getUpdateCount() == -1);
prep = conn.prepareStatement("DELETE FROM TEST");
prep.executeUpdate();
......
......@@ -47,7 +47,7 @@ public class TestAutoServer extends TestBase {
};
for (String url : urls) {
try {
DriverManager.getConnection(url);
getConnection(url);
fail(url);
} catch (SQLException e) {
assertKnownException(e);
......
......@@ -18,6 +18,7 @@ import java.sql.SQLException;
import org.h2.constant.ErrorCode;
import org.h2.constant.SysProperties;
import org.h2.test.TestBase;
import org.h2.test.utils.AssertThrows;
import org.h2.tools.Server;
import org.h2.util.IOUtils;
import org.h2.util.StringUtils;
......@@ -50,24 +51,18 @@ public class TestWeb extends TestBase {
}
private void testWrongParameters() throws Exception {
try {
Server.createPgServer("-pgPort 8182");
fail();
} catch (SQLException e) {
assertEquals(ErrorCode.FEATURE_NOT_SUPPORTED_1, e.getErrorCode());
}
try {
Server.createTcpServer("-tcpPort 8182");
fail();
} catch (SQLException e) {
assertEquals(ErrorCode.FEATURE_NOT_SUPPORTED_1, e.getErrorCode());
}
try {
new AssertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1) {
public void test() throws SQLException {
Server.createPgServer("-pgPort 8182");
}};
new AssertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1) {
public void test() throws SQLException {
Server.createTcpServer("-tcpPort 8182");
}};
new AssertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1) {
public void test() throws SQLException {
Server.createWebServer("-webPort=8182");
fail();
} catch (SQLException e) {
assertEquals(ErrorCode.FEATURE_NOT_SUPPORTED_1, e.getErrorCode());
}
}};
}
private void testAlreadyRunning() throws Exception {
......
......@@ -11,7 +11,6 @@ import org.h2.constant.ErrorCode;
import org.h2.engine.ConnectionInfo;
import java.io.File;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
......@@ -39,13 +38,13 @@ public class TestConnectionInfo extends TestBase {
private void testConnectInitError() throws Exception {
try {
DriverManager.getConnection("jdbc:h2:mem:;init=error");
getConnection("jdbc:h2:mem:;init=error");
fail();
} catch (SQLException e) {
assertEquals(ErrorCode.SYNTAX_ERROR_2, e.getErrorCode());
}
try {
DriverManager.getConnection("jdbc:h2:mem:;init=runscript from 'wrong.file'");
getConnection("jdbc:h2:mem:;init=runscript from 'wrong.file'");
fail();
} catch (SQLException e) {
assertEquals(ErrorCode.IO_EXCEPTION_2, e.getErrorCode());
......
......@@ -14,10 +14,11 @@ import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import org.h2.constant.ErrorCode;
import org.h2.constant.SysProperties;
import org.h2.message.DbException;
import org.h2.store.Data;
import org.h2.test.TestBase;
import org.h2.test.utils.AssertThrows;
import org.h2.util.DateTimeUtils;
import org.h2.util.New;
import org.h2.value.Value;
......@@ -264,18 +265,12 @@ public class TestDate extends TestBase {
assertEquals(0, ValueTimestamp.parse("+1970-01-01T00:00:00.000Z").getTimestamp().getTime());
assertEquals(0, ValueTimestamp.parse("1970-01-01T00:00:00.000+00:00").getTimestamp().getTime());
assertEquals(0, ValueTimestamp.parse("1970-01-01T00:00:00.000-00:00").getTimestamp().getTime());
try {
new AssertThrows(ErrorCode.INVALID_DATETIME_CONSTANT_2) { public void test() {
ValueTimestamp.parse("1970-01-01 00:00:00.000 ABC");
fail();
} catch (DbException e) {
// expected
}
try {
}};
new AssertThrows(ErrorCode.INVALID_DATETIME_CONSTANT_2) { public void test() {
ValueTimestamp.parse("1970-01-01T00:00:00.000+ABC");
fail();
} catch (DbException e) {
// expected
}
}};
}
private void testAbsoluteDay() {
......
......@@ -66,12 +66,10 @@ public class TestFileLock extends TestBase implements Runnable {
String url = "jdbc:h2:" + getBaseDir() + "/fileLock;FILE_LOCK=FS;OPEN_NEW=TRUE";
Connection conn = DriverManager.getConnection(url);
try {
DriverManager.getConnection(url);
getConnection(url);
fail();
} catch (SQLException e) {
if (e.getErrorCode() != ErrorCode.DATABASE_ALREADY_OPEN_1) {
throw e;
}
assertEquals(ErrorCode.DATABASE_ALREADY_OPEN_1, e.getErrorCode());
}
conn.close();
}
......
......@@ -9,6 +9,7 @@ package org.h2.test.unit;
import java.math.BigInteger;
import java.util.Random;
import org.h2.test.TestBase;
import org.h2.test.utils.AssertThrows;
import org.h2.util.MathUtils;
/**
......@@ -65,12 +66,9 @@ public class TestMathUtils extends TestBase {
}
private void testFactorial() {
try {
new AssertThrows(IllegalArgumentException.class) { public void test() {
factorial(-1);
fail();
} catch (IllegalArgumentException e) {
// ignore
}
}};
assertEquals("1", factorial(0).toString());
assertEquals("1", factorial(1).toString());
assertEquals("2", factorial(2).toString());
......
......@@ -209,7 +209,7 @@ public class TestServlet extends TestBase {
// listener must be stopped
try {
DriverManager.getConnection("jdbc:h2:tcp://localhost:8888/" + getBaseDir() + "/servlet", getUser(), getPassword());
getConnection("jdbc:h2:tcp://localhost:8888/" + getBaseDir() + "/servlet", getUser(), getPassword());
fail();
} catch (SQLException e) {
assertKnownException(e);
......
......@@ -13,6 +13,7 @@ import java.util.Date;
import java.util.Random;
import org.h2.message.DbException;
import org.h2.test.TestBase;
import org.h2.test.utils.AssertThrows;
import org.h2.util.DateTimeUtils;
import org.h2.util.StringUtils;
......@@ -45,18 +46,12 @@ public class TestStringUtils extends TestBase {
assertEquals(new byte[] { (byte) 0xfa, (byte) 0xce }, StringUtils.convertHexToBytes("face"));
assertEquals(new byte[] { (byte) 0xfa, (byte) 0xce }, StringUtils.convertHexToBytes("fAcE"));
assertEquals(new byte[] { (byte) 0xfa, (byte) 0xce }, StringUtils.convertHexToBytes("FaCe"));
try {
new AssertThrows(DbException.class) { public void test() {
StringUtils.convertHexToBytes("120");
fail();
} catch (DbException e) {
assertKnownException(DbException.toSQLException(e));
}
try {
}};
new AssertThrows(DbException.class) { public void test() {
StringUtils.convertHexToBytes("fast");
fail();
} catch (DbException e) {
assertKnownException(DbException.toSQLException(e));
}
}};
}
private void testPad() {
......
......@@ -35,6 +35,7 @@ import org.h2.store.FileLister;
import org.h2.store.fs.FileSystem;
import org.h2.test.TestBase;
import org.h2.test.trace.Player;
import org.h2.test.utils.AssertThrows;
import org.h2.tools.Backup;
import org.h2.tools.ChangeFileEncryption;
import org.h2.tools.Console;
......@@ -431,7 +432,7 @@ public class TestTools extends TestBase {
result = runServer(0, new String[]{"-tcpShutdown", "ssl://localhost:9001", "-tcpPassword", "abcdef"});
assertTrue(result.indexOf("Shutting down") >= 0);
try {
DriverManager.getConnection("jdbc:h2:ssl://localhost:9001/mem:", "sa", "sa");
getConnection("jdbc:h2:ssl://localhost:9001/mem:", "sa", "sa");
fail();
} catch (SQLException e) {
assertKnownException(e);
......@@ -458,7 +459,7 @@ public class TestTools extends TestBase {
assertTrue(result.indexOf("Shutting down") >= 0);
stop.shutdown();
try {
DriverManager.getConnection("jdbc:h2:tcp://localhost:9006/mem:", "sa", "sa");
getConnection("jdbc:h2:tcp://localhost:9006/mem:", "sa", "sa");
fail();
} catch (SQLException e) {
assertKnownException(e);
......@@ -739,7 +740,7 @@ public class TestTools extends TestBase {
org.h2.Driver.load();
String url = "jdbc:h2:" + getBaseDir() + "/utils";
String user = "sa", password = "abc";
String fileName = getBaseDir() + "/b2.zip";
final String fileName = getBaseDir() + "/b2.zip";
DeleteDbFiles.main("-dir", getBaseDir(), "-db", "utils", "-quiet");
Connection conn = DriverManager.getConnection(url, user, password);
conn.createStatement().execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR)");
......@@ -752,20 +753,19 @@ public class TestTools extends TestBase {
ResultSet rs = conn.createStatement().executeQuery("SELECT * FROM TEST");
assertTrue(rs.next());
assertFalse(rs.next());
try {
// must fail when the database is in use
Backup.main("-file", fileName, "-dir", getBaseDir(), "-db", "utils");
fail();
} catch (SQLException e) {
assertKnownException(e);
}
new AssertThrows(ErrorCode.CANNOT_CHANGE_SETTING_WHEN_OPEN_1) {
public void test() throws SQLException {
// must fail when the database is in use
Backup.main("-file", fileName, "-dir", getBaseDir(), "-db", "utils");
}
};
conn.close();
DeleteDbFiles.main("-dir", getBaseDir(), "-db", "utils", "-quiet");
}
private void testChangeFileEncryption(boolean split) throws SQLException {
org.h2.Driver.load();
String dir = (split ? "split:19:" : "") + getBaseDir();
final String dir = (split ? "split:19:" : "") + getBaseDir();
String url = "jdbc:h2:" + dir;
DeleteDbFiles.execute(dir, "utils", true);
Connection conn = DriverManager.getConnection(url + "/utils;CIPHER=XTEA", "sa", "abc 123");
......@@ -780,13 +780,12 @@ public class TestTools extends TestBase {
conn = DriverManager.getConnection(url + "/utils;CIPHER=AES", "sa", "def 123");
stat = conn.createStatement();
stat.execute("SELECT * FROM TEST");
try {
args = new String[] { "-dir", dir, "-db", "utils", "-cipher", "AES", "-decrypt", "def", "-quiet" };
ChangeFileEncryption.main(args);
fail();
} catch (SQLException e) {
assertKnownException(e);
}
new AssertThrows(ErrorCode.CANNOT_CHANGE_SETTING_WHEN_OPEN_1) {
public void test() throws SQLException {
ChangeFileEncryption.main(new String[] {
"-dir", dir, "-db", "utils", "-cipher", "AES", "-decrypt", "def", "-quiet" });
}
};
conn.close();
args = new String[] { "-dir", dir, "-db", "utils", "-quiet" };
DeleteDbFiles.main(args);
......@@ -807,28 +806,27 @@ public class TestTools extends TestBase {
"-tcpPassword", "abc",
"-baseDir", getBaseDir(),
"-tcpPort", "9192").start();
// should not be able to create new db
try {
DriverManager.getConnection("jdbc:h2:tcp://localhost:9192/test2", "sa", "");
fail("should not be able to create new db");
getConnection("jdbc:h2:tcp://localhost:9192/test2", "sa", "");
} catch (SQLException e) {
assertKnownException(e);
}
conn = DriverManager.getConnection("jdbc:h2:tcp://localhost:9192/test", "sa", "");
conn.close();
try {
Server.shutdownTcpServer("tcp://localhost:9192", "", true, false);
fail("shouldn't work and should throw an exception");
} catch (SQLException e) {
assertKnownException(e);
}
new AssertThrows(ErrorCode.WRONG_USER_OR_PASSWORD) {
public void test() throws SQLException {
Server.shutdownTcpServer("tcp://localhost:9192", "", true, false);
}};
conn = DriverManager.getConnection("jdbc:h2:tcp://localhost:9192/test", "sa", "");
// conn.close();
Server.shutdownTcpServer("tcp://localhost:9192", "abc", true, false);
// check that the database is closed
deleteDb("test");
// server must have been closed
try {
DriverManager.getConnection("jdbc:h2:tcp://localhost:9192/test", "sa", "");
fail("server must have been closed");
getConnection("jdbc:h2:tcp://localhost:9192/test", "sa", "");
fail();
} catch (SQLException e) {
assertKnownException(e);
}
......@@ -847,8 +845,8 @@ public class TestTools extends TestBase {
conn.close();
try {
DriverManager.getConnection("jdbc:h2:tcp://localhost:9192/../test", "sa", "");
fail("Should throw an exception!");
getConnection("jdbc:h2:tcp://localhost:9192/../test", "sa", "");
fail();
} catch (SQLException e) {
assertKnownException(e);
}
......
......@@ -16,8 +16,8 @@ import java.sql.Timestamp;
import java.sql.Types;
import java.util.UUID;
import org.h2.constant.ErrorCode;
import org.h2.message.DbException;
import org.h2.test.TestBase;
import org.h2.test.utils.AssertThrows;
import org.h2.tools.SimpleResultSet;
import org.h2.value.DataType;
import org.h2.value.Value;
......@@ -75,15 +75,12 @@ public class TestValue extends TestBase {
assertEquals(32, v.convertPrecision(10, false).getBytes()[9]);
assertEquals(10, v.convertPrecision(10, true).getPrecision());
v = ValueDecimal.get(new BigDecimal("1234567890.123456789"));
assertEquals(19, v.getPrecision());
assertEquals("1234567890.1234567", v.convertPrecision(10, true).getString());
try {
v.convertPrecision(10, false);
fail();
} catch (DbException e) {
assertEquals(ErrorCode.NUMERIC_VALUE_OUT_OF_RANGE_1, e.getErrorCode());
}
final Value vd = ValueDecimal.get(new BigDecimal("1234567890.123456789"));
assertEquals(19, vd.getPrecision());
assertEquals("1234567890.1234567", vd.convertPrecision(10, true).getString());
new AssertThrows(ErrorCode.NUMERIC_VALUE_OUT_OF_RANGE_1) { public void test() {
vd.convertPrecision(10, false);
}};
v = ValueLobDb.createSmallLob(Value.CLOB, spaces.getBytes(), 100);
assertEquals(100, v.getPrecision());
......@@ -230,29 +227,23 @@ public class TestValue extends TestBase {
}
private void testModulusDouble() {
ValueDouble vd1 = ValueDouble.get(12);
final ValueDouble vd1 = ValueDouble.get(12);
new AssertThrows(ErrorCode.DIVISION_BY_ZERO_1) { public void test() {
vd1.modulus(ValueDouble.get(0));
}};
ValueDouble vd2 = ValueDouble.get(10);
ValueDouble vd3 = vd1.modulus(vd2);
assertEquals(2, vd3.getDouble());
try {
vd1.modulus(ValueDouble.get(0));
fail();
} catch (DbException e) {
assertEquals(ErrorCode.DIVISION_BY_ZERO_1, e.getErrorCode());
}
}
private void testModulusDecimal() {
ValueDecimal vd1 = ValueDecimal.get(new BigDecimal(12));
final ValueDecimal vd1 = ValueDecimal.get(new BigDecimal(12));
new AssertThrows(ErrorCode.DIVISION_BY_ZERO_1) { public void test() {
vd1.modulus(ValueDecimal.get(new BigDecimal(0)));
}};
ValueDecimal vd2 = ValueDecimal.get(new BigDecimal(10));
ValueDecimal vd3 = vd1.modulus(vd2);
assertEquals(2, vd3.getDouble());
try {
vd1.modulus(ValueDecimal.get(new BigDecimal(0)));
fail();
} catch (DbException e) {
assertEquals(ErrorCode.DIVISION_BY_ZERO_1, e.getErrorCode());
}
}
private void testModulusOperator() throws SQLException {
......
......@@ -6,6 +6,9 @@
*/
package org.h2.test.utils;
import java.sql.SQLException;
import org.h2.message.DbException;
/**
* Helper class to simplify negative testing. Usage:
* <pre>
......@@ -19,6 +22,11 @@ public abstract class AssertThrows {
public AssertThrows(final Class<? extends Exception> expectedExceptionClass) {
this(new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread t, Throwable e) {
if (e == null) {
throw new AssertionError("Expected an exception of type " +
expectedExceptionClass.getSimpleName() +
", but no exception was thrown");
}
if (!expectedExceptionClass.isAssignableFrom(e.getClass())) {
AssertionError ae = new AssertionError(
"Expected an exception of type\n" +
......@@ -30,23 +38,47 @@ public abstract class AssertThrows {
throw ae;
}
}
}, "Expected an exception of type " +
expectedExceptionClass.getSimpleName() +
", but the test was successful");
});
}
public AssertThrows() {
this(new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread t, Throwable e) {
if (e != null) {
throw new AssertionError(
"Expected an exception to be thrown, but the test was successful");
}
// all exceptions are fine
}
}, "Expected an exception to be thrown, but the test was successful");
});
}
private AssertThrows(Thread.UncaughtExceptionHandler handler, String expected) {
public AssertThrows(final int expectedErrorCode) {
this(new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread t, Throwable e) {
int errorCode;
if (e instanceof DbException) {
errorCode = ((DbException) e).getErrorCode();
} else if (e instanceof SQLException) {
errorCode = ((SQLException) e).getErrorCode();
} else {
errorCode = 0;
}
if (errorCode != expectedErrorCode) {
AssertionError ae = new AssertionError(
"Expected an SQLException or DbException with error code " + expectedErrorCode);
ae.initCause(e);
throw ae;
}
}
});
}
private AssertThrows(Thread.UncaughtExceptionHandler handler) {
try {
test();
throw new AssertionError(expected);
handler.uncaughtException(null, null);
} catch (Exception e) {
handler.uncaughtException(null, e);
}
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论