在 Spock 单元测试中,未调用模拟方法

In Spock unit test mocked method is not being called

我正在尝试使用 Spock framework 实现单元测试,我的测试是这样的:

    def setup() {
        scrollableResultsMock = Mock(ScrollableResults)
        paymentRepositoryMock = Mock(PaymentRepository)

        paymentRegistryService = new PaymentRegistryService(paymentRepositoryMock)
    }

    @Unroll
    def 'should correctly process'() {
        given:
        paymentRepositoryMock.findUnconfirmedTransactions(_ as LocalDate, _ as Days) >> scrollableResultsMock
        ...
    }

这里是 class,我试图在其中注入模拟对象:

@Service
open class PaymentRegistryService
@Autowired
constructor(
        val paymentRepository: PaymentRepository
) {

    @Transactional
    open fun parseRegistryFileStream(input: InputStream): LinkedList<Pair<Long, String>> {
        ...
        val registry = paymentRepository.findUnconfirmedTransactions(start, PERIOD)
        ...
    }
}

虽然 运行 测试而不是调用我的方法,但正在调用真正的 paymentRepository 方法。我不明白可能是什么原因。 LocalDateDays 来自 Joda time 最后这是 paymentRepository class:

@Repository
@Transactional
open class PaymentRepository : AbstractRepository<Payment, Long>(Payment::class.java) {

    fun findUnconfirmedTransactions(start: LocalDate, days: Days): ScrollableResults = criteria().add(
            and(
                    eq("isConfirmed", false),
                    ge("transactionDateTime", start),
                    lt("transactionDateTime", start.plus(days))
            )).setCacheMode(CacheMode.IGNORE).scroll(ScrollMode.FORWARD_ONLY)

}

请试试这个:

open fun findUnconfirmedTransactions(start: LocalDate, days: Days): ScrollableResults

Mocking 需要扩展函数,除非函数在 Kotlin 中打开,否则 Spock 将无法这样做。