Я создал тест интеграции в Grails 2.x с пурпурой тестирования нескольких контроллеров, чтобы имитировать полный поток пользователей в веб-приложении.тест интеграции интеграции Grails 2
Сначала я сохранил две простые записи объектов домена, создавая экземпляры двух экземпляров контроллера в моем тестовом примере. Эти два простых класса: - Категория (категория продукта) и - Магазин (мини-рынок, на котором продаются продукты) Я написал два метода тестирования для управления экземплярами контроллера (StoreController и CategoryController) и работал нормально, одна запись категории был создан и несколько записей магазинов.
Затем я написал третий метод, чтобы попытаться сохранить запись продукта. Эта запись должна ссылаться на категорию. Итак, я беру экземпляр категории из предыдущих методов и пытаюсь передать его в ProductController среди других параметров продукта.
По неизвестной причине я могу только создавать записи продукта через экземпляр веб-приложения, набирая данные в веб-браузерах, но не по коду тестового класса. Я думаю, проблема связана с отношением между Продуктом и категорией, но я не мог понять, как мне передать параметры ProductController из моего тестового примера, чтобы создать новую запись продукта.
Это мой класс продукта:
class Product {
int id
String barCode
String shortDesc
String longDesc
String format
Category category
static belongsTo = [category: Category]
//static hasManySurveyRecord = [surveyRecord: SurveyRecord]
static constraints = {
id editable: false
barCode blank: false, nullable: false, maxSize: 64
shortDesc blank: false, nullable: false, maxSize: 32
longDesc blank: false, nullable: false, maxSize: 128
category blank: false
}
static mapping = {
table 'product_catalog'
version false
columns {
id column: 'id'
barCode column: 'bar_code'
shorDesc column: 'short_desc'
longDesc column: 'long_desc'
format column: 'format'
}
}
String toString() {
return longDesc
}
}
Это мой Категория класс:
class Category {
int id
String description
static hasManyProduct = [products: Product]
static constraints = {
id editable: false
description blank: false, nullable: false, maxSize: 64
}
static mapping = {
table 'categories'
version false
columns {
id column: 'id'
description column: 'description'
}
}
String toString() {
return description
}
}
Это моя интеграция тест для этого приложения:
static transactional = false
static storeList = []
static storesData = []
static categoryIns
static categoryData = []
static productIns = new Product()
static productData = []
@Before
void setup() {
storesData.add([zipCode: 926260001, address: "first test avenue, first city, CA" , description: "first testing store"])
storesData.add([zipCode: 926260002, address: "second test avenue, second city, CA" , description: "second testing store"])
storesData.add([zipCode: 926260003, address: "third test avenue, third city, CA" , description: "third testing store"])
storesData.add([zipCode: 926260004, address: "fourth test avenue, fourth city, CA" , description: "fourth testing store"])
storesData.add([zipCode: 926260005, address: "fifth test avenue, fifth city, CA" , description: "fifth testing store"])
storesData.add([zipCode: 926260006, address: "sixth test avenue, sixth city, CA" , description: "sixth testing store"])
storesData.add([zipCode: 926260007, address: "seventh test avenue, seventh city, CA", description: "seventh testing store"])
storesData.add([zipCode: 926260008, address: "eighth test avenue, eighth city, CA" , description: "eighth testing store"])
categoryData = [description: "testing category"]
productData = [barCode: "0114B", shorDesc: "The short testing description", longDesc: "The long testing description ....", format: "1 LT"]
}
@Test
void _01__createStores() {
def storeCtl = new StoreController()
(0..7).each { i ->
def model = storeCtl.create()
assert model.storeInstance != null
storeCtl.response.reset()
storeCtl.params.putAll(storesData.get(i))
storeCtl.save()
assert Store.count() == (i+1)
}
storeList.addAll(Store.list())
assert storeList.size() == Store.list().size()
}
@Test
void _02__createCategory() {
// Test if there is a previous store list created
assert storeList.size() == Store.list().size()
def categoryCtl = new CategoryController()
def model = categoryCtl.create()
assert model.categoryInstance != null
categoryCtl.response.reset()
categoryCtl.params.putAll(categoryData)
categoryCtl.save()
assert Category.count() == 1
categoryIns = Category.list()[0]
}
@Test
void _03__createProduct() {
// Test if there is a previous store list created
assert storeList.size() == Store.list().size()
// Test if there is a previous category created
assert categoryIns != null
assert categoryIns.id > 0
def productCtl = new ProductController()
def model = productCtl.create()
assert model.productInstance != null
productCtl.response.reset()
productData.put("category", [id: categoryIns.id])
productData.put("category.id", categoryIns.id)
productCtl.params.putAll(productData)
//productCtl.params.category = Category.get(categoryIns.id)
productCtl.save()
assert Product.count() == 1
}
Это мой ProductController код:
def save() {
def productInstance = new Product(params)
if (!productInstance.save(flush: true)) {
render(view: "create", model: [productInstance: productInstance])
return
}
flash.message = message(code: 'default.created.message', args: [message(code: 'product.label', default: 'Product'), productInstance.id])
redirect(action: "show", id: productInstance.id)
}
Извините, Утверждение, что сбой, является «утвердить Product.count() == 1» в методе тестирования «void _03__createProduct()». Это только последний. Спасибо – donkanmcleod
После 'productCtl.save()' проверьте ошибки вашего компонента: 'println productCtl.errors' –
Или используйте' .save (failOnError: true) 'для исключения исключений при неудачной проверке или сохранении. – Bart