How can I improve my junit tests

后端 未结 9 800
南笙
南笙 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:01

    Now you are testing many things in one method (a violation of One Assertion Per Test). This is a bad thing, because when any of those things changes, the whole test fails. This leads it to not being immediately obvious why a test failed and what needs to be fixed. Also when you intentionally change the behaviour of the system, you need to change more tests to correspond the changed behaviour (i.e. the tests are fragile).

    To know what kind of tests are good, it helps to read more on BDD: http://dannorth.net/introducing-bdd http://techblog.daveastels.com/2005/07/05/a-new-look-at-test-driven-development/ http://jonkruger.com/blog/2008/07/25/why-behavior-driven-development-is-good/

    To improve the test that you mentioned, I would split it into the following three test classes with these context and test method names:

    Creating user accounts

    • Before a user is created
      • the user does not exist
    • When a user is created
      • the user exists
    • When a user is deleted
      • the user does not exist anymore

    Logging in

    • When a user exists
      • the user can login with the right password
      • the user can not login with a wrong password
    • When a user does not exist
      • the user can not login

    Sending messages

    • When a user sends a message
      • the message appears in the sender's outbox
      • the message appears in the reciever's inbox
      • the message does not appear in any other message boxes
    • When a message is deleted
      • the message does not anymore exist

    You also need to improve the speed of the tests. You should have a unit test suite with good coverage, which can run in a couple of seconds. If it takes longer than 10-20 seconds to run the tests, then you will hesitate to run them after every change, and you lose some of quick feedback that running the tests gives you. (If it talks to the database, it's not a unit test, but a system or integration test, which have their uses, but are not fast enough to be executed continually.) You need to break the dependencies of the classes under test by mocking or stubbing them. Also from your description it appears that your tests are not isolated, but instead the tests depend on the side-effects caused by previous tests - this is a no-no. Good tests are FIRST.

提交回复
热议问题