2011-11-15 104 views
4

我想編寫一個JUnit測試來驗證是否可以通過GWT RPC過程成功地序列化一個特定的對象。我將如何做到這一點?我正在使用GWT 2.4和JUnit 4.8.1。測試GWT序列化

謝謝, - 戴夫

+0

您是否已升級到GWT 2.6或2.7?似乎接受的答案不再有效。你有沒有找到一種方法來測試最新的GWT? – sixtyfootersdude

回答

1

找到了答案。它是

@Test 
public void testObjSerializability() { 
    final Object obj = getObject(); 
    final HostedModeClientOracle hmco =new HostedModeClientOracle(); 
    final HasValues command = new ReturnCommand(); 
    final HasValuesCommandSink hvcs = new HasValuesCommandSink(command); 
    final CommandServerSerializationStreamWriter out = new CommandServerSerializationStreamWriter(hmco, hvcs); 
    try { 
     out.writeObject(obj); 
    } catch (Exception e) { 
     e.printStackTrace(System.err); 
     fail("Object couldn't be serialized:" + e.getMessage());    
    } 
} 
+1

此測試通過此類: 公共類MyClass實現了IsSerializable私有文件文件; public MyClass(String fileName){ this.file = new File(fileName); } } 雖然https://developers.google.com/web-toolkit/doc/1.6/DevGuideServerCommunication#DevGuideSerializableTypes需要無參數構造函數。這裏有什麼問題? – Alex

+0

從GWT 2.6或2.7'HostedModeClientOracle','HasValues','HasValuesCommandSink'和'CommandServerSerializationStreamWriter'已被刪除。 – sixtyfootersdude

4

接受的答案不檢查無參數構造函數;如下:

public static void checkGwtSerializability(Object o) throws RuntimeException { 
    HostedModeClientOracle hmco = new HostedModeClientOracle(); 
    HasValues command = new ReturnCommand(); 
    HasValuesCommandSink hvcs = new HasValuesCommandSink(command); 
    CommandServerSerializationStreamWriter out = new CommandServerSerializationStreamWriter(hmco, hvcs); 

    try { 
     out.writeObject(o); 
    } catch (SerializationException e) { 
     throw new RuntimeException("Object not serializable: " + o + " Caused by: " + e.getMessage(), e); 
    } 

    try { 
     o.getClass().getDeclaredConstructor(); 
    } catch (NoSuchMethodException e) { 
     throw new RuntimeException("Object not serializable: " + o + " Caused by: " + e.getMessage(), e); 
    } 
} 
+0

這也無法檢查對象的字段是否具有無參數構造函數。 –

+0

從GWT 2.6或2.7'HostedModeClientOracle','HasValues','HasValuesCommandSink'和'CommandServerSerializationStreamWriter'已被刪除。 – sixtyfootersdude