5

findOrCreateBy如果找不到匹配的对象,我正在尝试使用它来搜索对象或实例化一个对象,但它没有按预期工作。

这就是我所拥有的:

String myBaz = "some unique string"
FooType myFooType = FooType.findByName("Large")

// The Foo table is empty, so this should give me a new Foo
Foo myFoo = Foo.findOrCreateByBazAndFooType(myBaz, myFooType)

assert myFoo.baz == myBaz 
assert myFoo.fooType == myFooType // Fails because myFoo.fooType is null, 
// but should be set to myFooType

我究竟做错了什么?为什么fooType没有正确设置?这是预期的行为还是 Grails 中的错误?

4

1 回答 1

1

我不确定,但看起来您正在尝试将其作为测试。(根据您的断言)

Grails 框架添加的动态方法在单元测试中不可用,除非您模拟域类。现在这是从另一个问题站点获取的旧 grails 代码,但它可能会有所帮助

import grails.test.GrailsUnitTestCase   

class MessageControllerTests extends GrailsUnitTestCase {   

    def savedMessages   

    void setUp() {   
        super.setUp()   
        savedMessages = []   
        mockDomain(Message, savedMessages) //mocking the domain class   
        mockController(MessageController) //mocking the controller   
    }   

    void testMessageCanBeCreated() {   
        def messageController = new MessageController()   
        messageController.params.title = 'detail'  
        messageController.params.detail = 'some detail'  

        messageController.save() // executing the save action on the MessageController   

        assertEquals('list', messageController.redirectArgs.action)   
        assertEquals(1, savedMessages.size()) //assert the message has been saved   
    }   
}  
于 2012-07-17T18:31:32.217 回答