简体   繁体   English

Bean比较的单元测试框架

[英]Unit-test framework for bean comparison

Is there any good framework for comparing whole objects? 有没有比较整个对象的良好框架?

now i do 现在我做

assertEquals("ha@gmail.com", obj.email);
assertEquals("5", obj.shop);

if bad email is returned i never get to know if it had the right shop, i would like to get a list of incorrect fields. 如果退回了错误的电子邮件,我永远不会知道它是否有合适的商店,我想获得不正确字段的列表。

Going with the 1 test, 1 assert line of thinking if you has each assert in its own test you would know if one or both of these had failed by the fact that there were 1 or 2 failing tests. 进行1个测试,1个断言的思路后,如果您在自己的测试中拥有每个断言,您将通过存在1个或2个失败的测试这一事实而知道其中一个或两个都失败了。

@Test
public void TestEmail()
{
    obj = GetTestObject();
    assertEquals("ha@gmail.com", obj.email);
}

@Test
public void TestShop()
{
    obj = GetTestObject();
    assertEquals("5", obj.shop);
}

obviously you need to move the setup of the object into a method ot have it performed in the test set up method and have it a class variable. 显然,您需要将对象的设置移动到方法中,以使其在测试设置方法中执行,并使其具有类变量。

If you actually want to test if all properties are set in a single test: 如果您实际上要测试是否在单个测试中设置了所有属性,请执行以下操作:

@Test
public void TestAllProperties()
{
    obj = GetTestObject(); 
    bool testResult=true;
    string failureString;
    if "ha@gmail.com".equals( obj.email) == false
    {
         testResult=false;
         failureString+="email was different";
    }
    if "5".equals( obj.shop) == false
    {
         testResult=false;
         failureString+="shop was different";
    }
    assertTrue(testResult,failurestring);
}

but I'm not sure what this gives you really. 但我不确定这到底能给您带来什么。

But if you really want to compare the whole objects equality then override the equals method (not forgetting getHashCode too) and do your equality checking in there. 但是,如果您真的想比较整个对象的相等性,则重写equals方法(也不要忘记getHashCode)并在那里进行相等性检查。 after all that is what it is for... 毕竟这是为了...

If you want a list of incorrect fields you could make the equals method populate an internal list which you could query if the equality check failed, to get the list of failed fields the last time equality was checked. 如果要获取不正确字段的列表,可以使equals方法填充内部列表,您可以查询是否相等检查失败,以获取上次检查相等时失败字段的列表。 Don't really think that's a good idea though. 不过,不要真的认为这是个好主意。

You can also implement the comparable interface. 您还可以实现可比较的接口。

http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Comparable.html http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Comparable.html

I would go for hamcrest matchers. 我会去参加hamcrest比赛。 They allow me to write code like this: 它们允许我编写如下代码:

assertThat(obj, hasProperty("email", equalTo("ha@gmail.com")));

如果要测试对象相等性,那么肯定需要实现equals()并使用assertEquals()进行测试,否则Sam是正确的,每个测试一个声明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM