IllegalStateException:不能为带有 Kotlin 业务逻辑的 Spock 单元测试的 null

IllegalStateException: must not be null of Spock unit test with Kotlin business logic

我尝试让 MongoTemplate(Spring 数据)与我的 Spock 规格测试一起使用。我使用 Kotlin 作为业务逻辑语言。

请看我的规范逻辑:

@SpringBootTest
class BookingServiceSpec extends Specification {

    BookingService bookingService;
    BookingEntity bookingEntity
    CustomerEntity customerEntity
    MongoTemplate mongoTemplate;

    def setup() {
        bookingEntity = GroovyMock(BookingEntity)
        customerEntity = GroovyMock(CustomerEntity)
        mongoTemplate = Mock()
        bookingService = new BookingService(mongoTemplate)

        customerEntity.getEmail() >> "test@test.com"
        mongoTemplate.find(!null, !null, !null) >> List.of(bookingEntity)
    }

    def "should return a list of bookings if asked for bookings for a customer"() {
        when: "booking service is used to find bookings for a given customer"
        List<BookingEntity> bookings = bookingService.getBookings(customerEntity)
        then: "it should call the find method of the mongo template and return a list of booking entities"
        1 * mongoTemplate.find(!null, !null, !null)
    }
}

运行 此代码抛出一个 IllegalStateException 详细信息:

java.lang.IllegalStateException: mongoTemplate.find(query…::class.java, "bookings") must not be null

    at com.nomadsolutions.areavr.booking.BookingService.getBookings(BookingService.kt:22)
    at com.nomadsolutions.areavr.booking.BookingServiceSpec.should return a list of bookings if asked for bookings for a customer(BookingServiceSpec.groovy:37)

实体数据类定义如下:

data class CustomerEntity(val surname: String, val name: String, val email: String)
data class BookingEntity(val customerEntity: CustomerEntity, val date: Date)

这是业务逻辑:

@Service
class BookingService(var mongoTemplate: MongoTemplate) {

    fun addBooking(booking: BookingEntity) {
        mongoTemplate.insert(booking)
    }

    fun getBookings(customerEntity: CustomerEntity): List<BookingEntity> {
        val query = Query()
        query.addCriteria(Criteria.where("customer.email").`is`(customerEntity.email))
        return mongoTemplate.find(query, BookingEntity::class.java, "bookings")
    }

}

我发现 customerEntity 的存根无法正常工作,因为 customerEntity.email 在通过测试 运行.[=19 进行调试时在逻辑中返回 null =]

我很想继续使用 Spock,但它似乎阻碍了我快速测试,因为我必须关心这样的事情。

setup() 方法中删除这一行:

    mongoTemplate.find(!null, !null, !null) >> List.of(bookingEntity)

并将测试用例then部分的交互测试改成这样:

then: 'it should call the find method of the mongo template and return a list of booking entities'
1 * mongoTemplate.find(!null, !null, !null) >> [bookingEntity]

这是因为当您模拟和存根相同的方法调用时(mongoTemplate.find() 在您的情况下)它应该发生在相同的交互中。

您可以在 documentation 中阅读更多相关信息。