0

In JUnit is there a place where I can define how methods to be tested should flow?

I have class called Location which I have written a test for. All tests pass apart from testGetName which is called before testSetName.

It makes the tests fail. How can I fix this?

public class LocationTest {

    Location instance;

    @Before
    public void setUp() {
        instance = new Location();
    }              

    @Test
    public void testGetLongitude() {
        System.out.println("getLongitude");
        double expResult = 0.0;
        double result = instance.getLongitude();
        assertEquals(expResult, result, 0.0);
    }    

    @Test
    public void testSetLongitude() {
        System.out.println("setLongitude");
        double longitude = 0.0;
        instance.setLongitude(longitude);
    }    

    @Test
    public void testSetName() {
        System.out.println("setName");
        String name = "";
        instance.setName(name);
    }

    /**
     * Test of getName method, of class Location.
     */
    @Test
    public void testGetName() {
        System.out.println("getName");
               String expResult = "Mock Location";
        String result = instance.getName();
        assertEquals(expResult, result);
    }

}
Paul Rooney
  • 17,518
  • 8
  • 35
  • 57
Some Body
  • 13
  • 4
  • 2
    Oh dear, don't do this. Test the required behaviour of your class. Don't write a test for each individual method. And frankly, writing tests for getters and setters is really not a good use of your time. – Dawood ibn Kareem Sep 24 '18 at 01:31
  • @DawoodibnKareem, I agree 100% with that last point especially when we have things like [`auto-value`](https://github.com/google/auto/blob/master/value/userguide/index.md) designed specifically to eliminate the need to write all the redundancies of value classes – smac89 Sep 24 '18 at 23:45

1 Answers1

3

Short answer: No there isn't.

Long answer: Pretty sure there is a question already asked here on SO about this topic.

In general, tests should not maintain state from test to test, so if you have a getter test that depends on a setter test, chances are that you are doing the test wrong.

If you want to test getters and setters, do it all in one test; i.e. Test the setter by using the getter and if both operations are successful, then the getter and setter work!


To answer your question, there is one help JUnit has to offer with respect to this and it is found here:

https://github.com/junit-team/junit4/wiki/test-execution-order

In short, the options you have to ordering your tests are to either rely on the order the JVM specifies, or lexicographic ordering of the method names. These will not solve your problem because you seem to want a very specific order; i.e. set -> get

smac89
  • 26,360
  • 11
  • 91
  • 124