我正在为我的一些计算时间的代码编写单元测试。 我使用 SQL.date 作为输入并将其转换为日历进行计算。 (是的,我知道乔达会更好)。
我的测试如下:
def objectOrgUnit = Stub(ConOrgUnit)
def notification
def setup(){
objectOrgUnit = Stub(ConOrgUnit) {
getLogicalName() >> "Multimedia"
}
}
def "CreateNotification creates Notification with correctly caluclated dates"() {
given:
def date = new java.sql.Date(2020-1900,4,1)
def not = new NotificationGenerator()
def contract = GroovyMock(GenericBean) {
getCtrInsuranceDateToDat() >> date
}
def vocs = GroovyStub(ControlledVocabularyAccess) {
getNodesByInstanceAndName('TasStatusVgr', 'open') >> [Stub(ControlledVocabularyNode)]
getNodesByInstanceAndName('TasTypeVgr', 'TYPE') >> [Stub(ControlledVocabularyNode)]
}
def newNotification = GroovyMock(GenericBean) {
getTasContract02Ref() >> GroovyMock(GenericBean)
getTasSendEmailGrp() >> GroovyMock(GenericBean)
}
def dataAccess = GroovyStub(DataAccess) {
createObject("Task") >> newNotification
}
def orgUnitAdminService = Stub(OrgUnitAdminServiceAccess) {
readUsingLogicalName("org") >> objectOrgUnit
}
not.metaClass.vocs = vocs
not.metaClass.dataAccess = dataAccess
not.metaClass.orgUnitAdminService = orgUnitAdminService
when:
notification = not.createNotification(contract, 2, "REASON", "TYPE", "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a5f1e0f6f1e8e4ece9e5e8e4ece98be6eae8" rel="noreferrer noopener nofollow">[email protected]</a>", "org")
then:
1 * newNotification.setTasDeadlineDat(2020-02-01)
1 * newNotification.setTasDeadlineToDat(2020-02-01)
}
运行时,它给我错误:
1 * newNotification.setTasDeadlineDat(2020-02-01) (0 invocations)
Unmatched invocations (ordered by similarity):
1 * newNotification.setTasDeadlineDat(2020-02-01)
所以看起来这是正确的? 我还尝试测试“日期”,但这也不起作用。
代码本身是这样的(部分):
Calendar c = Calendar.getInstance()
c.setTime(contract.CtrInsuranceDateToDat)
c.add(Calendar.MONTH, -1 * (months + 1))
taskNotification.TasDeadlineDat = new java.sql.Date(c.getTime().getTime())
taskNotification.TasDeadlineToDat = new java.sql.Date(c.getTime().getTime())
最佳答案
好吧,我无法运行你的测试,但我想我发现了它:
then:
1 * newNotification.setTasDeadlineDat(2020-02-01)
1 * newNotification.setTasDeadlineToDat(2020-02-01)
2020-02-01
只是一个减法 2020 - 2 - 1
或 2017
,不是日期,也不是简单的 Java 日期也不是 SQL 日期(它是 Java 日期的子类,所以要小心)。
我认为你更想要的是这样的:
given:
def expectedDate = new SimpleDateFormat("yyyy-MM-dd").parse("2020-02-01")
// ...
then:
1 * newNotification.setTasDeadlineDat(expectedDate)
1 * newNotification.setTasDeadlineToDat(expectedDate)
现在您实际上是在比较日期。它适用于比较 java.sql.Date 和 java.util.Date 因为后者不会重写 equals(..) 方法前者。
关于groovy - Spock UnitTest,调用太少,但 "Unmatched invocations"列表中的调用完全相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62338848/