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

问题描述 投票:0回答:1

我尝试在我的Spock规格测试中获得MongoTemplate(Spring数据)。我使用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() >> "[email protected]"
        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在逻辑中返回了null

我很乐意继续使用Spock,但是由于我不得不关心类似的事情,这似乎使我无法进行快速测试。

spring unit-testing kotlin spock
1个回答
0
投票

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中了解更多相关信息。

© www.soinside.com 2019 - 2024. All rights reserved.