findOrCreateBy是否可以与其他域实例一起使用?

cde*_*zaq 5 grails grails-orm dynamic-finders

我正在尝试使用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
Run Code Online (Sandbox Code Playgroud)

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

PJT*_*PJT 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   
    }   
}  
Run Code Online (Sandbox Code Playgroud)