1

我的 GAE 课程之一是从 HTML 文件创建 [datastore Entity][1]:

Key parent = KeyFactory.createKey("movies", "movies");
Entity movie = new Entity("movie",System.currentTimeMillis(), parent);
setIfNotEmpty(movie, "director",    Jsoup.parse(Html).select("td#f3").text());
setIfNotEmpty(movie, "year",        Jsoup.parse(Html).select("td#f17").text());
....

当我尝试在 JUnit 测试中调用此方法时,会引发以下异常:

java.lang.NullPointerException: No API environment is registered for this thread.
    at com.google.appengine.api.datastore.DatastoreApiHelper.getCurrentAppId(DatastoreApiHelper.java:80)
    at com.google.appengine.api.datastore.DatastoreApiHelper.getCurrentAppIdNamespace(DatastoreApiHelper.java:90)
    at com.google.appengine.api.datastore.Key.<init>(Key.java:97)
    at com.google.appengine.api.datastore.Key.<init>(Key.java:87)
    at com.google.appengine.api.datastore.KeyFactory.createKey(KeyFactory.java:85)
    at com.google.appengine.api.datastore.KeyFactory.createKey(KeyFactory.java:78)
    at com.google.appengine.api.datastore.KeyFactory.createKey(KeyFactory.java:66)
    at cinemasderot.Movie.parseMovieHtml(Movie.java:21)
    at tests.TestParsing.testAddition(TestParsing.java:24)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
    .....

问题似乎是在我的代码示例的第一行中创建了 Key。

如何使用 Junit 测试中的父键创建实体?

4

1 回答 1

4

请阅读:https ://developers.google.com/appengine/docs/java/tools/localunittesting

简而言之,你需要这样的东西:

private final LocalServiceTestHelper helper =
    new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());

@Before
public void setUp() {
    helper.setUp();
}

@After
public void tearDown() {
    helper.tearDown();
}
于 2013-04-25T07:36:44.567 回答