如何在JUnit中解决"你还没有开始一个Objectify上下文"?

Mic*_*sky 11 google-app-engine objectify google-cloud-datastore

我在JUnit中运行了一些Objectify测试代码,我收到了这个错误:

java.lang.IllegalStateException: You have not started an Objectify context. You are probably missing the ObjectifyFilter. If you are not running in the context of an http request, see the ObjectifyService.run() method.
    at com.googlecode.objectify.ObjectifyService.ofy(ObjectifyService.java:44)
    at com.googlecode.objectify.impl.ref.LiveRef.<init>(LiveRef.java:31)
    at com.googlecode.objectify.Ref.create(Ref.java:26)
    at com.googlecode.objectify.Ref.create(Ref.java:32)
    at com.netbase.followerdownloader.repository.DownloadTaskRepositoryImpl.create(DownloadTaskRepositoryImpl.java:35)
    at com.netbase.followerdownloader.repository.DownloadTaskRepositoryImplTest.setUp(DownloadTaskRepositoryImplTest.java:45)
Run Code Online (Sandbox Code Playgroud)

如何为测试代码解决此问题?

Mic*_*sky 11

Jeff Schnitzer在此处回答:https://groups.google.com/forum/#!topic / objectify-appengine/8HinahG7irg .该链接指向https://groups.google.com/forum/#!topic/objectify-appengine/O4FHC_i7EGk,Jeff建议以下快速而肮脏的解决方法:

  • 我的@BeforeMethod启动了一个客观化的上下文(ObjectifyService.begin())

  • 我的@AfterMethod关闭了客观化的背景

杰夫建议我们改用ObjectifyService.run()它,但承认它更有用.

以下是我的实现的外观:

public class DownloadTaskRepositoryImplTest {
    // maximum eventual consistency (see https://cloud.google.com/appengine/docs/java/tools/localunittesting)
    private final LocalServiceTestHelper helper =
        new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig()
            .setDefaultHighRepJobPolicyUnappliedJobPercentage(100));

    private Closeable closeable;

    @Before
    public void setUp() {
        helper.setUp();
        ObjectifyRegistrar.registerDataModel();
        closeable = ObjectifyService.begin();
    }

    @After
    public void tearDown() {
        closeable.close();

        helper.tearDown();
    }
Run Code Online (Sandbox Code Playgroud)

  • @Michael ......你在哪里得到了"ObjectifyRegistrar?" (3认同)
  • 这个解决方案根本行不通,"ObjectifyRegistrar"不存在 (2认同)

Kob*_*her 8

我也有这个问题,并注意到我没有将ObjectifyFilter添加到我的web.xml中

<filter>
    <filter-name>ObjectifyFilter</filter-name>
    <filter-class>com.googlecode.objectify.ObjectifyFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>ObjectifyFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
Run Code Online (Sandbox Code Playgroud)

我还必须在我的WEB-INF> lib目录中包含Objectify和guava jar,并将它们包含在我的构建路径中.