我正在使用 DbUnit 测试我的 DAO 层。我正在从 XML 数据集预填充数据库,执行一些操作,然后针对已知结果进行断言。
Assertion.assertEquals(expectedDataSet, actualDataSet);
数据集包含带有浮点数的列。然后比较这些列,我得到:
junit.framework.ComparisonFailure: value (table=OrderLine_T, row=2, col=price) expected:<2.99[]> but was:<2.99[0000009536743]>.
值相等,但由于浮点数不能以二进制形式精确表示,因此断言失败。在 JUnit 中,我们有assertEquals(double expected, double actual, double delta)
. 我们如何在 DbUnit 中设置一些增量来进行浮点数比较?
初始数据集:
<dataset>
<Customer_T id="1" name="Anthony"/>
<Customer_T id="2" name="John"/>
<Order_T id="1" date="2012-06-07 14:30" customer_id="1" />
<Order_T id="2" date="2012-06-07 15:31" customer_id="2" />
<OrderLine_T id="1" order_id="1" product_id="1" price="2.99" quantity="5" />
<OrderLine_T id="2" order_id="2" product_id="2" price="3.49" quantity="10" />
</dataset>
预期结果:
<dataset>
<Customer_T id="1" name="Anthony"/>
<Customer_T id="2" name="John"/>
<Order_T id="1" date="2012-06-07 14:30" customer_id="1" />
<Order_T id="2" date="2012-06-07 15:31" customer_id="2" />
<OrderLine_T id="1" order_id="1" product_id="1" price="2.99" quantity="5" />
<OrderLine_T id="2" order_id="2" product_id="2" price="3.49" quantity="10" />
<!-- Below added -->
<Order_T id="3" date="1987-06-07 9:15:10" customer_id="2" />
<OrderLine_T id="3" order_id="3" product_id="1" price="2.99" quantity="2" />
<OrderLine_T id="4" order_id="3" product_id="5" price="3.55" quantity="8" />
</dataset>
代码:
/* Should save order correctly (including order lines) */
@Test
public void save() throws Exception {
/* Create new order */
Set<OrderLine> lines = new HashSet<OrderLine>();
lines.add(new OrderLine(1, (float)2.99, 2));
lines.add(new OrderLine(5, (float)3.55, 8));
Calendar cal = Calendar.getInstance();
cal.set(1987, 6, 7, 9, 15, 10);
Date date = cal.getTime();
Customer customer = customerDAO.findById(2); // John
Order order = new Order(date, lines, customer);
orderDAO.save(order);
entityManager.flush();
/* Assert order is saved */
IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(Thread.currentThread()
.getContextClassLoader()
.getResourceAsStream("data-set-afterAddOrder.xml"));
IDataSet actualDataSet = getDatabaseConnection().createDataSet();
Assertion.assertEquals(expectedDataSet, actualDataSet);
}
编辑:
可能需要提及我正在使用的内存 HSQLDB。刚试了mysql,成功通过了。
尝试设置ToleratedDelta
没有成功:
IDatabaseConnection connection = new DatabaseConnection(((SessionImpl) (entityManager.getDelegate())).connection());
HsqldbDataTypeFactory dataTypeFactory = new HsqldbDataTypeFactory();
dataTypeFactory.addToleratedDelta(new ToleratedDelta("OrderLine_T", "price", 0.01));
connection.getConfig().setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, dataTypeFactory);
编辑2:
我正在使用 hibernate.hbm2ddl.auto = create,将架构导出到数据库。从 fredt得到想法后,我将实体上的字段价格类型更改为 BigDecimal 并添加了额外的列精度和比例参数:
@Column(precision=10, scale=4)
private BigDecimal price;
这被翻译成PRICE NUMERIC(10,4)
. 问题解决了,感谢fredt。