如何为Google App Engine单元测试设置已经一致的数据?

时间:2015-05-05 04:01:09

标签: java unit-testing google-app-engine google-cloud-endpoints

我知道App Engine数据存储区查询最终只是一致的。但是,对于我的一些测试,我想用已经一致的数据为数据存储区播种(即它在测试发生之前保存了很长时间,现在全局一致)。

如何在运行测试之前确保初始数据是否一致?我仍然希望能够要求被测试的行动不需要立即保持一致。

我使用的是Google Cloud Endpoints for Java,但我并不是特定于端点的任何内容。

1 个答案:

答案 0 :(得分:0)

我最终创建了以下BaseTest类,并让我的所有测试继承自:

package com.example;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.dev.HighRepJobPolicy;
import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;

import org.junit.After;
import org.junit.Before;
import org.junit.Rule;

public class BaseTest {
  public static final class Policy implements HighRepJobPolicy {
    static boolean shouldApply = false;

    public static void applyAll() {
      shouldApply = true;
    }

    public static void applyNone() {
      shouldApply = false;
    }

    @Override
    public boolean shouldApplyNewJob(Key entityGroup) {
      return shouldApply;
    }

    @Override
    public boolean shouldRollForwardExistingJob(Key entityGroup) {
      return shouldApply;
    }
  }

  public final LocalServiceTestHelper helper =
      new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig()
          .setAlternateHighRepJobPolicyClass(Policy.class));

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

  @After
  public void tearDown() {
    helper.tearDown();
  }
}

然后测试可以采用以下形式:

@Test
public void thingShouldDoX() throws Exception {
  Policy.applyAll();
  // Do setup here, everything inside will be consistent.
  Policy.applyNone();
  // Run code under test here, without consistency.
}