gpt4 book ai didi

scala - 为什么 java.util.Date 对象满足一项 Specs 测试但未通过另一项测试?

转载 作者:行者123 更新时间:2023-12-02 03:57:20 25 4
gpt4 key购买 nike

我正在尝试使用 Play Framework 2.0 和 Specs2 测试模型方法。 Global.scala 在第一次运行时使用数据填充数据库。在一项测试中,我可以使用如下代码成功测试它:

def dateHelper(str: String): Date = new SimpleDateFormat("MM/dd/yyyy").parse(str)

"Food model" should {
"be retrieved by id" in {
val Some(mashedPotatoes) = Food.findById(1000)

mashedPotatoes.name must equalTo("Mashed Potatoes")
mashedPotatoes.eaten must equalTo(false)
mashedPotatoes.id must equalTo(Id(1000))
mashedPotatoes.owner must equalTo(Id(1))
mashedPotatoes.expiry must equalTo(dateHelper("05/21/2012"))
}
}

测试通过了。但是,如果我尝试从模型中选择多个项目,并将其作为列表进行测试:

"return food for test user in " in {

running(FakeApplication()) {
val testFoods: Seq[Food] = Food.findFoodFor(Id(1)) // Test user's ID is 1

// This test fails
testFoods must equalTo(
List(
Food(Id(1001), "Fried Green Tomatoes", false, Id(1), dateHelper("04/21/2012")),
Food(Id(1000), "Mashed Potatoes", false, Id(1), dateHelper("05/21/2012"))
)
)

// This test passes
testFoods.head.expiry must equalTo(dateHelper("04/21/2012"))
}
}

错误输出告诉我日期字段不相等:

[error] x return food for test user in
[error] 'Food(1001,Fried Green Tomatoes,false,1,2012-04-21 00:00:00.0), Food(1000,Mashed Potatoes,false,1,2012-05-21 00:00:00.0)' is not equal to 'Food(1001,Fried Green Tomatoes,false,1,Sat Apr 21 00:00:00 EDT 2012), Food(1000,Mashed Potatoes,false,1,Mon May 21 00:00:00 EDT 2012)' (ModelSpec.scala:66)
[error] Expected: ...se,1,[Sat Apr ]21...00[ EDT 2]0[12]),...1,[Mon May ]21...00[ EDT 2]0[12])
[error] Actual: ...se,1,[2012-04-]21...00[.]0[]),...1,[2012-05-]21...00[.]0[])

这里有我遗漏的东西吗?

编辑:看起来是数据库架构将到期列设置为时间戳类型,而不是日期类型。

这里有更多有用的信息:java.util.Date vs java.sql.Date

最佳答案

问题可能是由于从数据库加载数据的方式造成的。我打赌它正在使用 java.sql.Timestamp而不是java.util.Date .

scala> val date = dateHelper("05/12/1974")
d: java.util.Date = Sun May 12 00:00:00 CDT 1974

scala> val dbDate = new java.sql.Timestamp(d.getTime)
dbDate: java.sql.Timestamp = 1974-05-12 00:00:00.0

scala> date == dbDate
res6: Boolean = true

scala> dbDate == date // prepare to be amazed!
res5: Boolean = false

如果您阅读the fine print in the Javadoc ,你会发现这个漂亮的小声明:

Due to the differences between the Timestamp class and the java.util.Date class mentioned above, it is recommended that code not view Timestamp values generically as an instance of java.util.Date. The inheritance relationship between Timestamp and java.util.Date really denotes implementation inheritance, and not type inheritance.

您的 ORM 映射或数据库架构可能有问题。该列是 DATETIMESTAMPTIMESTAMP WITH TIMEZONE 吗?如果是 DATE,您应该将其映射到 java.sql.Date ,应该正确比较。如果它是 TIMESTAMP WITH TIMEZONE,那么您的 dateHelper 应该构建 Timestamp。如果是TIMESTAMP,祝你好运,因为数据库将丢失时区信息。

关于scala - 为什么 java.util.Date 对象满足一项 Specs 测试但未通过另一项测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9993157/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com