Initialize local datastore exception : No API environment is registered for this thread

后端 未结 3 1000
终归单人心
终归单人心 2021-01-04 11:38

I would like to initialize my local data store with some data using a regular Java program (I do not want to start the Development Server and call a service/servlet), and I\

相关标签:
3条回答
  • 2021-01-04 12:01

    Google provides a helper class that does exactly what you want - runs just enough code to work with the database, without launching the whole dev server. See the setUp and tearDown methods at http://code.google.com/appengine/docs/java/tools/localunittesting.html

    0 讨论(0)
  • 2021-01-04 12:10

    You have to setup a test Datastore Service for current thread. Basically you can do this:

    private static void testServerCallBack() {
        LocalServiceTestHelper helper =
            new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());
        helper.setUp();
        Contacts contacts = new Contacts("this is", "awesome");
        greetingServiceImpl.saveContact(contacts);//line:14
    }
    

    That will initialize Database Service (a fake, for testing only) for this method only.

    Or better you can do:

    private final LocalServiceTestHelper helper =
      new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());
    
    @Before
    public void setUp() {
       helper.setUp();
    }
    
    @After
    public void tearDown() {
       helper.tearDown();
    }
    

    So Database Service will work from all test methods.

    Notice that if you're using different threads to access db, then you'll get a separate database for each thread. That's not what you want most likely. I mean helper.setUp() do setup a new separate Database Service for current thread, and all data stored into this db will be accessible only from current thread.

    See more details at: http://code.google.com/appengine/docs/java/tools/localunittesting.html

    0 讨论(0)
  • 2021-01-04 12:13

    Just add those 3 libs (appart of the test one) to your classpath:

    ${SDK_ROOT}/lib/impl/appengine-api.jar
    ${SDK_ROOT}/lib/impl/appengine-api-labs.jar
    ${SDK_ROOT}/lib/impl/appengine-api-stubs.jar
    

    This should fix the problem.

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