Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

You're talking about things like dependency injection. I'm not a huge fan of testing but "testable code" when written in a certain way (without dependency injection) actually has many external benefits that don't have to do with testing per se.

Really the way you need to structure your program is to divide functions in your code between things that can be unit tested and can't (IO calls).

This can easily be done without dependency injection which is likely what you're complaining about.

For example Don't do this:

    #unit testable with mock (Bad!)
    function add_one(key: str, database: Database):
         return database.get(key) + 1
Or.. even worse:

    #Unit testable with mock (Bad!)
    class Adder
       Adder(database) -> None {
          this.database = database
       }

       add_one(key: str) -> int {
          return this.database.get(key) + 1
       }
Do this instead:

      #IO function, Not unit testable
      def get_database_value(key, database) -> None:
          return database.get(key)

      #Unit testable without mock! Good!
      def add_one(value: int) -> int:
          return value + 1

      #IO function, not unit testable. 
      def composition(key: str) -> int:
          return add_one(get_database_value("name"))


Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: