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

时间:2012-07-17 15:47:17

标签: grails gorm 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

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

1 个答案:

答案 0 :(得分:1)

我不确定,但看起来你试图做这个测试。 (根据你的断言)

除非您模拟域类,否则Grails框架添加的动态方法在单元测试中不可用。现在这是从另一个Question site 获取的旧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   
    }   
}