Using Blobstore from JUnit

2019-07-02 01:25发布

I am trying to test some code that uses the Blobstore API, but I don't really get how I am expected to get some files into the blobstore. The following is not working:

private BlobKey createBlob(String path) throws Exception {
    FileService fileService = FileServiceFactory.getFileService();
    AppEngineFile file = fileService.createNewBlobFile("foobar");
    FileWriteChannel writeChannel = fileService.openWriteChannel(file, true);
    OutputStream output = Channels.newOutputStream(writeChannel);

    // copy files, guava-style
    InputStream input = new FileInputStream(path);
    assertNotNull(input);
    ByteStreams.copy(input, output); 
    input.close();

    // just in case...
    output.flush();
    output.close();
    writeChannel.close();

    // U NO WORK!!!
    BlobKey blobKey = fileService.getBlobKey(file);
    assertNotNull(blobKey);
    return blobKey;
}

My config:

new LocalServiceTestHelper(
    new LocalBlobstoreServiceTestConfig()
        //.setNoStorage(true)
        .setBackingStoreLocation("war/WEB-INF/appengine-generated"),
    new LocalFileServiceTestConfig()
).setUp();

Any ideas?

1条回答
男人必须洒脱
2楼-- · 2019-07-02 01:50

The following test run successfully

public class TestBlobstore {
  private static final LocalServiceTestHelper helper = 
    new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig(),
                               new LocalBlobstoreServiceTestConfig()
                              );

  public TestBlobstore() {
  }

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

  @Test
  public void testBlobstore() throws Exception {
    System.out.println(createBlob("test.txt"));
  }

  private BlobKey createBlob(String path) throws Exception {
    FileService fileService = FileServiceFactory.getFileService();
    AppEngineFile file = fileService.createNewBlobFile("foobar");
    FileWriteChannel writeChannel = fileService.openWriteChannel(file, true);
    OutputStream output = Channels.newOutputStream(writeChannel);

    // copy files, guava-style
    InputStream input = new FileInputStream(path);
    assertNotNull(input);
    ByteStreams.copy(input, output); 
    input.close();

    // just in case...
    output.flush();
    output.close();
    writeChannel.closeFinally();

    // U NO WORK!!!
    BlobKey blobKey = fileService.getBlobKey(file);
    assertNotNull(blobKey);
    return blobKey;
  }
}

Two modifications:

  • User LocalBlobstoreServiceTestConfig instead of LocalFileServiceTestConfig
  • writeChannel.closeFinally(); instead of writeChannel.close()

Hope this help.

查看更多
登录 后发表回答