首页 文章

如何依靠Channel API(Google App Engine,Java)对代码进行单元测试

提问于
浏览
3

我有Java servlet,它依赖于来自Google App Engine的Channel API . 我正在尝试为该代码编写单元测试,但我非常难以理解如何编写存根客户端以从servlet接收响应消息,而不是总是依赖于使用实际网页作为我的测试客户端 . 我的servlet非常简单:

ChannelService channelService = ChannelServiceFactory.getChannelService();
channelService.sendMessage(new ChannelMessage(someKey, "ECHO: " + someMsg));

通常,我在我的测试客户端中读到这个,这是一个网页 . 但是,我想编写单元测试,我可以使用像jUnit或TestNG这样的框架进行测试 . 在阅读了Google的page about unit testing their Java services之后,我尝试了一些东西,例如在我的测试类中使用LocalServiceTestHelper对象并使用LocalChannelServiceTestConfig对象进行配置 . 结果是我的测试类可以创建一个 LocalChannelService 的实例,这个类似乎实现了与 ChannelService 相同的方法 .

However:

  • 这两个类之间没有任何健壮的关系(不实现类似的接口,不在同一个类层次结构中......) . 使我无法将LocalChannelService对象作为模拟对象注入到我的servlet中 .

  • 没有关于LocalChannelService API的任何文档(非常感谢,Google) .

  • 在本地单元测试页面上没有关于如何测试Channel API的文档(再次,非常感谢Google)

那么我遇到了关于如何在Java代码中测试 ChannelServicepost . 不幸的是,给出的唯一相关答案是Python . 嗯,瞧,Google确实为Python GAE服务器开发人员提供了为Google服务编写存根客户端的工具,如Python Local Unit Testing guide中所述 . 令人难以置信的是他们忽略了为Java做同样的事情!


现在我've gotten all that off my chest (apologies if I sounded a bit too flustered), I would really like to know, what is the best way for testing Java code relying on Google App Engine'的 Channels API?我真的希望依靠测试工具而不是网页 . 我是否必须以某种方式从Java中调用Google的Javascript Client for Channel API?必须有一种更好的方法可以使用模拟对象或存根 .


更新1

使用更好的名称,“Google App Engine”而不仅仅是“App Engine”

2 回答

  • 0

    这些只是我对Channel API的单元测试的想法:

    • 你不需要模拟 . 只需使用实际的API . 假装它有效 . 即使您的消息无法发送,它也不会返回任何故障,因此无论如何您都无法进行测试 .

    • 有备份 . 我认为你不能依赖Channel API . 消息无法显示 . 我个人认为你需要一个备份,就像一个不像Channel API那样响应的轮询API,但至少可行 .

    • 单元测试您的备份API .

    • 使用Selenium在浏览器中测试Channel API .

  • 4

    您可以从LocalServiceTestHelper获取LocalChannelService,将假客户端连接到它,然后从中获取消息:

    LocalChannelService svc = (LocalChannelService) LocalServiceTestHelper.getLocalService("channel");
        ChannelManager channelManager = svc.getChannelManager();
        String connectionId = channelManager.connectClient(token);
    
        // send a message
    
        String message = channelManager.getNextClientMessage(token, connectionId);
        assertEquals("123", message);
    

相关问题