Peter
Peter

Reputation: 231

How do you call a setup method into a test to stop re-writing the same code

I'm using java and Im trying to call a method into my tests to clean up the code. What is the best way to do this. Will it be to call the method or use the @Before on the setup method I've created. As you will see from the code below there are several repetitions. What will be the best way forward?

import com.pubnub.api.PubnubException;
import org.junit.Before;
import org.junit.Test;
import service.PubnubService;

/**
 * Created by peterki on 07/09/2016.
 */
public class PublisherTest {

    private PubnubService service = new PubnubService();

    @Before
    public void setupConnection() throws PubnubException {

        // Setup Subscriber
        service.subscribe("my_channel");

        // Do nothing until the subscriber has connected.
        do{} while (!service.isConnected());

    }

    @Test
    public void testPublisher() throws PubnubException {

        // Setup Subscriber
        service.subscribe("my_channel");

        // Do nothing until the subscriber has connected.
        do{} while (!service.isConnected());

        // Send 10 messages
        for(int i = 0; i <= 10; i++){
            service.publish("my_channel", "Message: " + i);
        }

        // Wait until we have recieved the 10 messages
        do{}while(service.count() <= 10);

        // For each message print out the details
        service.getMessages().forEach(System.out::println);
    }

    @Test
    public void testSportMessageType() throws PubnubException {
        // Setup Subscriber
        service.subscribe("my_channel");

        // Wait for Connection
        do{} while (!service.isConnected());

        // Publish to External Service

        //Wait till we receive the message

        // Assert the message is what we want
    }
}

Upvotes: 0

Views: 57

Answers (3)

marthursson
marthursson

Reputation: 3300

The common code in the test cases can easily be extracted to a method called from each individual test (or - if the same common code is present in all tests - just add them in the @Before)

But your tests will be fragile the way it's currently written. What happens if the service never connects (possibly because a new bug was introduced in the service code)? Your test will hang indefinitely instead of failing.

I would recommend awaitility for that kind of stuff.

Upvotes: 0

Jonathan Andersson
Jonathan Andersson

Reputation: 1432

@Before is called before each @Test. In other words it is a perfect place to do stuff that has to be prepared before the tests run.

I would say that service.subscribe("my_channel"); is perfect to have in @Before.

Upvotes: 3

Ravikumar
Ravikumar

Reputation: 901

Instead of @Before you can use @BeforeClass if you want your service to established only once (like a DB connection) otherwise @Before is perfect.

Upvotes: 0

Related Questions