简体   繁体   中英

Junit testing dependent methods

I'm having trouble with Junit testing, and can find little info online.

Firstly, I want to test 2 methods,

1. setTable(int r, int c, String s)

2. getTableString() .

I managed to test the first one, but the second one requires that the table be already built (the table being a private static char[][] with a getter, and is built by the first method).

How do I go about testing this second method? I thought of doing this:

    public void testGetTableString() {

        MyClass test = new MyClass();
        test.setTable(5, 4, "string");
        String toTest = test.getTableString();
        assertEquals("expected result", toTest);
    }

This however doesn't seem right since it's dependent on setTable working.

I also thought of initializing test.setTable(5,4,"string") in the setUp() method, but that would mean that I'd have to change the parameters for setTable in the setUp() method each time and not be able to track my tests; plus it would setUp() for my first method too, which I don't want.

Any help is greatly appreciated.

RE: This however doesn't seem right since it's dependent on setTable working.

What you have done is perfectly appropriate. If getTableString() is the method-under-test, then the best way to isolate it is to setup the necessary pre-conditions. Also, by putting the setTable call right in this test method, you have isolated these conditions to this one test (as opposed to putting the call in setup() which will be seen by all test methods).

Just because you have two methods (to test) doesn't mean there has to be two methods to test them. You can club that in a single junit test.

Since they are related, you cant really say setXY works unless you verify with getXY

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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