How can I improve my junit tests

后端 未结 9 773
南笙
南笙 2020-12-05 08:59

Right my junit tests look like a long story:

  • I create 4 users
  • I delete 1 user
  • I try to login with the deleted user and make sure it fails
相关标签:
9条回答
  • 2020-12-05 09:23

    You can use JExample, an extension of JUnit that allows test methods to have return values that are reused by other tests. JExample tests run with the normal JUnit plugin in Eclipse, and also work side by side with normal JUnit tests. Thus migration should be no problem. JExample is used as follows

    @RunWith(JExample.class)
    public class MyTest {
    
        @Test
        public Object a() { 
            return new Object();
        }
    
        @Test
        @Given("#a")
        public Object b(Object object) { 
            // do something with object
            return object; 
        }
    
        @Test
        @Given("#b")
        public void c(Object object) { 
            // do some more things with object
        }
    
    }
    

    Disclaimer, I am among the JExample developers.

    0 讨论(0)
  • 2020-12-05 09:25

    unit tests should - ideally - be independent, and able to run in any order. So, I would suggest that you:

    • break up your tests to be independent
    • consider using an in-memory database as the backend for your tests
    • consider wrapping each test or suite in a transaction that is rolled back at the end
    • profile the unit tests to see where the time is going, and concentrate on that

    if it takes 8 minutes to create a few users and send a few messages, the performance problem may not be in the tests, rather this may be a symptom of performance problems with the system itself - only your profiler knows for sure!

    [caveat: i do NOT consider these kinds of tests to be 'integration tests', though i may be in the minority; i consider these kinds of tests to be unit tests of features, a la TDD]

    0 讨论(0)
  • 2020-12-05 09:25

    If you use TestNG you can annotate tests in a variety of ways. For example, you can annotate your tests above as long-running. Then you can configure your automated-build/continuous integration server to run these, but the standard "interactive" developer build would not (unless they explicitly choose to).

    This approach depends on developers checking into your continuous build on a regular basis, so that the tests do get run!

    Some tests will inevitably take a long time to run. The comments in this thread re. performance are all valid. However if your tests do take a long time, the pragmatic solution is to run them but not let their time-consuming nature impact the developers to the point that they avoid running them.

    Note: you can do something similar with JUnit by (say) naming tests in different fashions and getting your continuous build to run a particular subset of test classes.

    0 讨论(0)
提交回复
热议问题