Package gaej2011.hello

Source Code of gaej2011.hello.GuestbookServletTest

package gaej2011.hello;

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;

import java.util.Calendar;
import java.util.Date;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;

public class GuestbookServletTest {

  @Test
  public void saveToDatastore() {
    // テスト対象メソッドを実行する前の「Guestbook」エンティティの全件数を保持する
    DatastoreService datastoreService = DatastoreServiceFactory
        .getDatastoreService();
    Query query = new Query("Guestbook");
    int before = datastoreService.prepare(query).countEntities(
        FetchOptions.Builder.withDefaults());
    // GuestbookServlet.saveToDatastore を実行する
    GuestbookServlet.saveToDatastore(" 投稿内容");
    // テスト対象を実行すると「Guestbook」エンティティが1 件増えることを確認する
    int after = datastoreService.prepare(query).countEntities(
        FetchOptions.Builder.withDefaults());
    assertThat("Guestbook エンティティが1 件増えている", after, is(before + 1));
  }

  @Test
  public void queryFromDatastore() {
    DatastoreService datastoreService = DatastoreServiceFactory
        .getDatastoreService();
    Calendar calendar = Calendar.getInstance();
    for (int i = 0; i < 5; i++) { // 5 件保存しておく
      Entity entity = new Entity("Guestbook");
      entity.setProperty("message", " 投稿内容" + i);
      entity.setProperty("createdAt", calendar.getTime());
      datastoreService.put(entity);
      calendar.add(Calendar.HOUR_OF_DAY, 1); // 1 時間進める
    }
    int count = 0;
    Date before = null;
    Iterable<Entity> iterable = GuestbookServlet.queryFromDatastore();
    for (Entity entity : iterable) {
      Date createdAt = (Date) entity.getProperty("createdAt");
      if (before != null) {
        assertThat(" 新しいものから取得できている", before.compareTo(createdAt) > 0, is(true));
      }
      before = createdAt;
      count++;
    }
    assertThat(" 全てのエンティティが取得できている", count, is(5));
  }

  LocalServiceTestHelper helper;

  @Before
  public void setUp() {
    LocalDatastoreServiceTestConfig dsConfig = new LocalDatastoreServiceTestConfig();
    dsConfig.setNoStorage(true);
    helper = new LocalServiceTestHelper(dsConfig);
    helper.setUp();
  }

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

Related Classes of gaej2011.hello.GuestbookServletTest

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.