Testing a function where the output is mostly relying on helper functions



  • Let's say I want to test this function:

    foo(input){
       a = bar(input)
       if(a)
          return baz(0)
       return baz(1)
    }
    
    (pseudocode)
    

    I want to test foo in isolation, so i mock bar and baz, but if I mock bar the input becomes irrelevant. Unless the mocks care about their input, but then I'll mostly be testing my mockimplentation.

    I also I don't want to test internals, but see that the correct input delivers the correct output. If I mock bar, the output only relies on what I've told bar to return in its mock implementations.



  • Indeed, the input is "irrelevant" for checking this function.

    What does it do?

    1 - If the return of bar(input) is true, return baz(0)

    2 - If the return of bar(input) is false, return baz(1)

    How can you mock bar and baz to validate such a behavior?

    You can have two stubs of bar:

    • One that always returns true
    • One that always returns false

    And for baz, you can have a spy that will register the inputs of its calls.

    You would have one the test for case (1), you inject the stub with return true and check if the spy was called with zero. On the second test, you inject the stub with false and check if the spy was called with one.



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2