import static java.lang.Long.MAX_VALUE; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import org.junit.After; import org.junit.Before; import org.junit.Test; public class OverflowLongSumTest { @Test public void testIt() throws SQLException { insert(42); assertSum(42); // ok insert(MAX_VALUE - 42); assertSum(MAX_VALUE); // ok insert(1); assertSum(MAX_VALUE); // wrong, should raise an exception insert(5); assertSum(MAX_VALUE); // wrong, should raise an exception } private void insert(final long value) throws SQLException { try(Statement st = connection.createStatement()) { st.execute("INSERT INTO tab VALUES (" + value + ")"); } } private void assertSum(final long expected) throws SQLException { try( Statement st = connection.createStatement(); ResultSet rs = st.executeQuery("SELECT SUM(col) FROM tab")) { assertTrue(rs.next()); assertEquals(expected, rs.getLong(1)); } } private Connection connection; @Before public void before() throws SQLException { connection = DriverManager.getConnection("jdbc:mysql://localhost/xxx", "xxx", "xxx"); try(Statement st = connection.createStatement()) { st.execute("DROP TABLE IF EXISTS tab"); } try(Statement st = connection.createStatement()) { st.execute("CREATE TABLE tab ( col bigint )"); } } @After public void after() throws SQLException { try(Statement st = connection.createStatement()) { st.execute("DROP TABLE IF EXISTS tab"); } connection.close(); } }