Spock UnitTest,调用太少,但 "Unmatched invocations" 列表中的调用完全相同

Spock UnitTest, Too few invocations, but exact same invocation in "Unmatched invocations" list

我正在为我的一些计算时间的代码编写单元测试。 我使用 SQL.date 作为输入并将其转换为日历以进行计算。 (是的,我知道 Joda 会更好)。

我的测试如下:

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", "TESTMAIL@MAIL.COM", "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)

所以看起来是正确的? 我也试过测试 "date" 也不起作用。

代码本身是这样的(部分):

    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 - 12017,不是日期,既不是简单的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.Datejava.util.Date,因为后者不会覆盖前者的 equals(..) 方法。