如何测试该对象是否返回正确的字符串? [英] How can I test if this object returns the correct String?

查看:107
本文介绍了如何测试该对象是否返回正确的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Thing类,其中包含各种Strings和Stuff的集合. 我必须测试Message类是否可以正确地在MessageTest类中返回 item 作为找到" .

I have a Thing class that holds various Strings and a Collection of Stuff. I have to test whether the Message class can correctly return item as "found" in a MessageTest class.

最优雅/最有效的测试方法是什么?

What is the most elegant/efficient way of testing this?

我应该创建哪种伪造的对象,以及如何对其进行测试/反对?

What kind of fake object should I create, and how do I test with/against it?

public class Thing
{
    public String a;
    public String b;
    public String c;
    public String d;
    public String e;
    public Collection<Stuff> collection;
}

public class Message
{
    private String item;

    public Message(Thing thing)
    {
        for (Stuff stuff : thing.collection)
        {
            if (stuff.getItem().equals("key"))
            {
                item = "found";
            }
        }
    }


@Override
public String toString()
{
    StringBuilder builder = new StringBuilder();
    builder.append(a);
    builder.append(b);
    builder.append(c);
    builder.append(d);
    builder.append(e);
    builder.append(item);
    return builder.toString();
}
}

推荐答案

JUnit的想法是进行单元测试.我认为您应该测试一种特定的方法,该方法知道该怎么做,而不是伪造"任何东西(我理解mocking伪造),例如:

The idea of JUnit is to do unit testing. I think you should test a specific method that you know what it should do instead of "faking" anything (I understand mocking for faking), for example:

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class PayrollTesCase {

    @Test
    public void testCalculate() {
        Message m = new Message(new Thing("a", "b", "c", "d", "e"));
        assertEquals("abcde", m.toString());
    }

}

因此,如果将来更改Message.toString()实现,引入了一个错误,并且该错误返回"cde",则您的特定测试用例将失败.这就是单元测试的思想.

So, if in the future you change your Message.toString() implementation, you introduced a bug and it returns "cde" then your specific test case will fail. This is the idea behind unit testing.

我喜欢这个定义:

单元测试是软件测试过程的一个层次,其中 测试软件/系统的各个单元/组件.这 目的是验证软件的每个单元均按以下方式执行: 设计.

Unit Testing is a level of the software testing process where individual units/components of a software/system are tested. The purpose is to validate that each unit of the software performs as designed.

在JUnit 4.x中,所有方法都带有注释.因此,JUnit方法中的控制流程可以描述如下:

In JUnit 4.x all the methods are annotated. So, the flow of control in JUnit methods can be described as below:

@BeforeClass -> @Before -> @Test -> @After -> @AfterClass

顺便说一下,您有不同程度的测试,单元测试是最小的".我不确定您需要什么,但也许您想进行集成测试.

By the way, you have different degrees of testing, Unit Testing is the "smallest". I'm not sure what you need but maybe you want to do an Integration Test.

这篇关于如何测试该对象是否返回正确的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆