我尝试在我的Spock规格测试中使用MongoTemplate
(Spring Data)。我使用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
在逻辑中返回了null
。
我很乐意继续使用Spock,但是由于我不得不关心类似的事情,这似乎使我无法进行快速测试。
答案 0 :(得分:1)
从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中了解更多相关信息。