2012-07-17 2 views
5

findOrCreateByを使用して、オブジェクトを検索したり、一致するものが見つからない場合はインスタンス化したりしようとしていますが、期待通りに動作しません。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のバグですか?

+0

まあを助けるかもしれない、それは愚かなことかもしれませんが、あなたのデータベースが空であることから、FooType.findByName(「大」)は右、nullを返しますか?その後、このnull属性を渡すオブジェクトを作成します。だから、ええ、myFoo.fooTypeはこの場合実際にはnullでなければなりません。 –

+0

@TiagoFarias、私はこの点をより正確にするために質問を更新しました。 FooTypesはDBにブートストラップされているため、実際には空ではありませんが、FooオブジェクトはDBにありません。 'findOrCreate *'が呼ばれると、 'myFooType'は' FooType'の永続化されたインスタンスです。 – cdeszaq

答えて

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 
    } 
} 
+0

アサーションは問題を示すためだけにあります。これは実際にはサービスからのコードなので、GORMビットとボブはすべて存在しますが、 'findOrCreateBy *'は正しく動作しません。しかし、ありがとう。 – cdeszaq

関連する問題