• Xylight (Photon dev)@lemmy.xylight.dev
    link
    fedilink
    English
    arrow-up
    2
    ·
    1 年前

    I’ve been wanting to make my applications easier to test. The issue is, I don’t know what to test. Often my issues are so trivial I notice them immediately.

    What are some examples of common things in, let’s say a web server, that could be unit tested?

    • Vince@feddit.de
      link
      fedilink
      arrow-up
      1
      ·
      1 年前

      Good questions, I could probably write a lot, but I’ll try to keep it short. I usually apply TDD and there are different schools of thought within it about how to structure the development process. But no matter how exactly you do it, if you focus on writing the tests while writing your code, you won’t end up with an application that you then have to figure out how to test.

      what to test

      Well, what is the application supposed do? That is what you test, the behaviour of the application.

      So in a codebase without any tests, the first thing you should write a test for is the happy path. That will probably not be a unit test. So for the web server example, set it up in a test with a file, start it and check if it serves that file.

      Then you can add tests for all the error cases and for additional functionality. You can write unit tests for individual components. The ideal places to test are interfaces with clear boundaries. Ideally you should not have to look at the code of a method to be able to write a test for it. In reality that’s not always so easy, especially in existing code bases, but if you have to set up more than one mock, it tends to lead to brittle tests.

      Every time you encounter a bug/issue, reproduce it in a test first. And do measure code coverage, but don’t make it a target, just check for places that are lacking.