gpt4 book ai didi

spring - 非法状态异常 : must not be null of Spock unit test with Kotlin business logic

转载 作者:行者123 更新时间:2023-12-02 13:34:53 26 4
gpt4 key购买 nike

我尝试获取 MongoTemplate (Spring Data) 与我的 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 的 stub 从 customerEntity.email 开始无法正常工作正在返回 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]

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

您可以在 documentation 中了解更多信息。 .

关于spring - 非法状态异常 : must not be null of Spock unit test with Kotlin business logic,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58472995/

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