我的一个GAE课程是从HTML文件创建[数据存储区实体] [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)
.....
问题似乎是在我的代码示例的第一行创建了密钥。
如何使用Junit测试中的父键创建实体?
答案 0 :(得分: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();
}