stevendao
stevendao

Reputation: 954

How can I test if this object returns the correct String?

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();
}
}

Upvotes: 0

Views: 648

Answers (1)

Federico Piazza
Federico Piazza

Reputation: 30985

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());
    }

}

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.

I like this definition:

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.

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.

software testing hierarchy

Upvotes: 2

Related Questions