2012-06-23 42 views
3

我已經閱讀了AppEngine unit testing guidelines,並且我得到了Java Datastore服務測試的工作,但我對Channel服務沒有任何好運。本指南沒有給出任何具體的頻道測試例子,而且javadoc也沒有什麼幫助,但是我的IDE向我展示了一些類似於單元測試本地頻道服務的類;我無法弄清楚如何使用它們。如何單元測試AppEngine渠道服務?

有沒有人有任何經驗或例子測試GAE渠道服務?

回答

2

以下爲我工作:

import unittest 

from google.appengine.api import channel 
from google.appengine.ext import testbed 


class TestCase(unittest.TestCase): 

    def setUp(self): 
    self.testbed = testbed.Testbed() 
    self.testbed.activate() 
    self.testbed.init_channel_stub() 

    def test_send(self): 
    channel_stub = self.testbed.get_stub('channel') 
    token = channel.create_channel('ClientID1') 
    channel_stub.connect_channel(token) 
    channel.send_message('ClientID1', 'hello') 
    channel_messages = channel_stub.get_channel_messages(token) 
    channel_stub.clear_channel_messages(token) 
    self.assertEquals(['hello'], channel_messages) 


if __name__ == '__main__': 
    unittest.main() 

您也可以查看source code for the channel service stub

+0

我想我應該更清楚我使用的是Java。我似乎沒有在Google的Java測試API中看到相同的Testbed類。 –

1

Ivan提供了一個整潔的Python示例,下面是Java的解決方案。

Supppose這裏我們要測試的

public class ClientChannelService { 

    private ChannelService channelService = ChannelServiceFactory.getChannelService(); 

    public String createToken(){ 
     return channelService.createChannel(UUID.randomUUID().toString()); 
    } 

    public void sendMessage(String token, String message){ 
     channelService.sendMessage(new ChannelMessage(token, message)); 
    } 
} 

首先,添加appengine-testing.jar到classpath代碼:

<dependency> 
    <groupId>com.google.appengine</groupId> 
    <artifactId>appengine-testing</artifactId> 
    <version>${appengine.version}</version> 
    <scope>test</scope> 
</dependency> 

接下來,創建一個測試如下。我在這裏假設JUnit,但通常你可以自由地使用任何測試框架,GAE並不重要。

private ClientChannelService service; 
private LocalServiceTestHelper helper = new LocalServiceTestHelper(
              new LocalChannelServiceTestConfig()); 
private ChannelManager channelManager; 

@Before 
public void setUp() { 
    helper.setUp(); 
    channelManager = LocalChannelServiceTestConfig.getLocalChannelService() 
                .getChannelManager(); 
    service = new ClientChannelService(); 
} 

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

@Test 
public void testSendMessage() { 
    String token = service.createToken(); 
    connectionId = channelManager.connectClient(token); //emulate client connection 

    service.sendMessage(token, "message"); 

    String message = channelManager.getNextClientMessage(token, connectionId); 
    assertEquals("message", message); 
}