Objectify error “You cannot create a Key for an object with a null @Id” in JUnit

后端 未结 2 1415
悲&欢浪女
悲&欢浪女 2021-01-16 02:31

I got the following error while testing a simple piece of code in JUnit that creates a User object (an Objectify Entity) and then tries to attach it as a Parent

相关标签:
2条回答
  • 2021-01-16 03:08

    What's the type of 'id' in User class? If it's 'Long', keeping id=null should work. From what you explained, looks like it's 'long' (primitive). if that's the case, change it to 'Long' and try again.

    0 讨论(0)
  • 2021-01-16 03:09

    This is most likely caused by saving asynchronously instead of synchronously:

    Be careful when saving entities with an autogenerated Long @Id field. A synchronous save() will populate the generated id value on the entity instance. An asynchronous save() will not; the operation will be pending until the async operation is completed.

    Source: https://code.google.com/p/objectify-appengine/wiki/BasicOperations#Saving

    It should fix the problem to change the save() method

    From this:

    private void save(DownloadTask downloadTask) {
        Closeable closeable = begin();
        ofy().save().entity(downloadTask);
        closeable.close();
    }
    

    To this:

    private void save(DownloadTask downloadTask) {
        Closeable closeable = begin();
        ofy().save().entity(downloadTask).now();  // Added .now()
        closeable.close();
    }
    

    This fixed the problem for me in a similar situation where I was testing with Junit on a data model involving a linked object model.

    0 讨论(0)
提交回复
热议问题