grails 2.0.1单元测试保存时出现NullPointerException

时间:2012-07-02 10:03:55

标签: unit-testing grails mocking gorm

我在grails中遇到一个奇怪的单元测试问题,当我尝试保存一个模拟对象时会抛出一个NullPointerException

 java.lang.NullPointerException
at org.grails.datastore.mapping.engine.NativeEntryEntityPersister.persistEntity(NativeEntryEntityPersister.java:798)
at org.grails.datastore.mapping.engine.EntityPersister.persist(EntityPersister.java:130)
at org.grails.datastore.mapping.core.AbstractSession.persist(AbstractSession.java:477)
at org.grails.datastore.gorm.GormInstanceApi.doSave(GormInstanceApi.groovy:166)
at org.grails.datastore.gorm.GormInstanceApi$_save_closure4.doCall(GormInstanceApi.groovy:143)
at org.grails.datastore.mapping.core.DatastoreUtils.execute(DatastoreUtils.java:301)
at org.grails.datastore.gorm.AbstractDatastoreApi.execute(AbstractDatastoreApi.groovy:34)
at org.grails.datastore.gorm.GormInstanceApi.save(GormInstanceApi.groovy:142)
at it.rascio.ConverterServiceTests.testConvert(ConverterServiceTests.groovy:64)

我的测试结果如下:

@TestFor(ConverterService)
@TestMixin(GrailsUnitTestMixin)
@Mock([MyObj1, MyObj2, LittleObject])
class ConverterServiceTests{
   def littleObject;
   void setUp(){
         littleObject = new LittleObject(prop1: 'hello', prop2: 'world')
   }

   void testConvert(){
    MyObj1 obj = new MyObj1()
    obj.prop = 'my property'
    obj.littleObject = littleObject
    obj = obj.save(flush:true, failOnError: true)

    MyObj2 b = new MyObj2()
    b.obj1Id = obj.id;

    assert service.convert(b) == null;


}

当我调用 .save 方法时抛出异常。 我已经看到,如果我删除 littleObject 它可以工作。 有人可以知道这个例外是什么吗?

1 个答案:

答案 0 :(得分:6)

如果您的班级MyObj1包含其他类型的某些嵌入属性,或者有任何其他级联保存,则应将这些类添加到@Mock注释列表。