如何编写基于Google Cloud Endpoints的API测试?

Dmy*_*hyn 3 java testing google-app-engine maven google-cloud-endpoints

有什么方法可以测试使用JUnit或其他框架使用Google Cloud Endpoint编写的API?

在文档中,有一个使用curl命令的示例,其背后的逻辑也许是仅在客户端上测试API。

当我尝试找到一些方法来从服务器端测试API时,遇到了编写JUnit测试并将HttpURLConnection调用到localhost 的可能性,但是这种方法存在问题。例如,应用引擎的实例应该在测试之前已经运行,但是我使用maven在本地部署,并且测试是在部署之前,所以如果测试失败,则它不会部署dev服务器,我不认为这是正确的重写Maven步骤的方法。

编辑1:发现与Python类似的方法:如何对Google Cloud Endpoints进行单元测试

Dmi*_*sev 5

有了Objectify,您可以像这样。例如,让我们声明BooksEndpoint如下:

@Api(
    name = "books",
    version = "v1",
    namespace = @ApiNamespace(ownerDomain = "backend.example.com", ownerName = "backend.example.com", packagePath = "")
)
public class BooksEndpoint {

    @ApiMethod(name = "saveBook")
    public void saveBook(Book book, User user) throws OAuthRequestException, IOException {
        if (user == null) {
            throw new OAuthRequestException("User is not authorized");
        }

        Account account = AccountService.create().getAccount(user);

        ofy().save()
                .entity(BookRecord.fromBook(account, book))
                .now();
    }

}
Run Code Online (Sandbox Code Playgroud)

要测试它,您需要以下依赖项:

testCompile 'com.google.appengine:appengine-api-labs:1.9.8'
testCompile 'com.google.appengine:appengine-api-stubs:1.9.8'
testCompile 'com.google.appengine:appengine-testing:1.9.8'
testCompile 'junit:junit:4.12'
Run Code Online (Sandbox Code Playgroud)

现在,测试将如下所示:

public class BooksEndpointTest {

    private final LocalServiceTestHelper testHelper = new LocalServiceTestHelper(
            new LocalDatastoreServiceTestConfig()
    );

    private Closeable objectifyService;

    @Before
    public void setUp() throws Exception {
        testHelper.setUp();
        objectifyService = ObjectifyService.begin(); // required if you want to use Objectify
    }

    @After
    public void tearDown() throws Exception {
        testHelper.tearDown();
        objectifyService.close();
    }

    @Test
    public void testSaveBook() throws Exception {
        // Create Endpoint and execute your method
        new BooksEndpoint().saveBook(
                Book.create("id", "name", "author"),
                new User("example@example.com", "authDomain")
        );

        // Check what was written into datastore
        BookRecord bookRecord = ofy().load().type(BookRecord.class).first().now();

        // Assert that it is correct (simplified)
        assertEquals("name", bookRecord.getName());
    }

}
Run Code Online (Sandbox Code Playgroud)

请注意,我使用BookRecordBook在这里-这些都是我的实体和POJO,没什么特别的。