2016-08-18 24 views
0

我有相当多的类是Serializable/Externalizable类和不幸的是,它经常发生时,我忘记serailize/desirialize一个新领域时,将其添加到类或mispell readObject而不是readDouble。所以我决定写一些被忽略的单元测试,不会在maven-surefire-plugin下运行。这只是为了我自己的需要。它看起来像这样:如何比较两个对象的字段?

@Test(enabled = false) 
public void testEquality(Object o){ 
    String oPart = o.toString(); 
    try (FileOutputStream fos = new FileOutputStream("/home/myusr/testser/" + oPart); 
     ObjectOutputStream ous = new ObjectOutputStream(fos)) { 
     ous.writeObject(o); 
    } catch (FileNotFoundException | IOException e) { 
     e.printStackTrace(); 
    } 
    Object oo = null; 
    try (FileInputStream fis = new FileInputStream("/home/myusr/testser/" + oPart); 
     ObjectInputStream ois = new ObjectInputStream(fis)) { 
     Object oo = ois.readObject(); 
    } catch (FileNotFoundException | IOException | ClassNotFoundException e) { 
     e.printStackTrace(); 
    } 
    // Need to compare all non-transient fields of o and oo 
} 

但问题是如何比较这不是transient具有相同名称的所有领域。我不想重写equals方法仅用于测试目的。

有没有办法处理它?也许有一些commons/guava库可以解决这个问题。

+0

你见过[shazamcrest](https://github.com/shazam/shazamcrest)吗? –

回答

2

您可以使用反射来做它,从YourClaas.class.getDeclaredFields()开始。然后,您必须筛选返回的字段,从对象中检索值并进行比较。