我正在尝试为我的 Google App Engine 项目创建一个单元测试。用例如下:客户端向 API 查询上传 URL,由于数据需要存储在 blobstore 中,客户端接收到带有 URL 的 JSON 编码结构。然后客户端将数据上传到该 URL。
servlet 的实现相当简单:
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Gson gson = new Gson();
Map<String, String> result = new HashMap<String, String>();
result.put("uploadurl", BlobstoreServiceFactory.getBlobstoreService()
.createUploadUrl("/api/v1/import"));
gson.toJson(result, resp.getWriter());
}
以良好的方式应该进行测试以查看客户端是否确实收到了正确的数据。所以应该有一个反JUnit测试。我希望模拟 blob 存储服务,以便它返回一个固定的上传 url,然后测试可以检查它。
但是,我不知道如何否决 blobstore 服务。使用 Mockito 我无法模拟静态 getBlobstoreService(),使用 LocalBlobstoreServiceTestConfig 我不知道如何否决 createUploadUrl() 的答案。
我编写测试的尝试是这样的:
public class ImportServletTest {
public static class Response {
String uploadurl;
void setUploadurl(String url) {
this.uploadurl = url;
}
}
private LocalBlobstoreServiceTestConfig blobstoreConfig = new LocalBlobstoreServiceTestConfig();
private LocalServiceTestHelper helper = new LocalServiceTestHelper(blobstoreConfig);
@Test
public void getsUploadURL() throws IOException, ServletException {
ImportServlet servlet = new ImportServlet();
HttpServletResponse response = mock(HttpServletResponse.class);
try (CharArrayWriter output = new CharArrayWriter();
PrintWriter writer = new PrintWriter(output);) {
when(response.getWriter()).thenReturn(writer);
servlet.doGet(null, response);
writer.flush();
Response apiResponse = new Gson().fromJson(output.toString(), Response.class);
assertEquals("http://mysite/_ah/theurl", apiResponse.uploadurl);
}
}
@Before
public void setupGae() throws IOException {
helper.setUp();
}
@After
public void teardownGae() {
helper.tearDown();
}
}