我正在创建Grails 2.4.3应用程序,并具有以下Domain类:
class StockItem {
String name
BigDecimal wholesalePrice
BigDecimal retailPrice
BigDecimal profit
static belongsTo = [ledger: Ledger]
static constraints = {
name minSize:3, maxSize:255
wholesalePrice min:0.0, scale:2
retailPrice min:0.0, scale:2
retailPrice validator: { retailPrice, StockItem obj ->
if (retailPrice < obj.wholesalePrice) {
['retailLessThanWholesale']
}
}
}
static mapping = {
profit(formula: 'RETAIL_PRICE - WHOLESALE_PRICE')
}
}
class Ledger {
String name
static hasMany = [clients: Client, invoices: Invoice, availableItems: StockItem, payments: Payment]
static constraints = {
name unique:true
}
}
我有一个单元测试:
@Domain(StockItem)
@TestMixin(HibernateTestMixin)
class StockItemSpec extends Specification {
void "Test profit calculation"() {
when: "a stock item exists"
StockItem i = new StockItem(name: "pencil", wholesalePrice: 1.50, retailPrice: 2.75)
then: "profit is calculated correctly"
i.profit == 1.25
}
}
因此失败了:
Failure: Test profit calculation(com.waldoware.invoicer.StockItemSpec)
| org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory': Invocation of init method failed; nested exception is
org.hibernate.MappingException: An association from the table stock_item refers to an unmapped class: com.waldoware.invoicer.Ledger
该应用程序似乎运行正常,并且我不明白为什么该测试失败。任何想法表示赞赏!
最佳答案
由于您的belongsTo
和StockItem
域类之间存在Ledger
关联,因此您需要在测试中将Ledger
添加到@Domain
批注中:
@Domain([StockItem, Ledger])
初始化单元测试运行时时,这应该正确配置所需的域类。根据您的其他测试用例,您可能还需要在批注中包括
Client
或Payment
。
关于exception - Grails GORM关联未映射异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25935578/