How to mock nested functions?

前端 未结 4 1120
南旧
南旧 2020-12-06 04:10

The mocking library I use is ... mock.

I came across this \"mock nested functions\" problem when I tried to write test case for a function(legacy code).

This

4条回答
  •  攒了一身酷
    2020-12-06 05:11

    One option is to change your function so that it optionally accepts the function to call e.g. if you have:

    def fn_to_test():
      def inner_fn():
        return 1
      return inner_fn() + 3
    

    Change it to:

    def fn_to_test( inner_fn = null )
      def inner_fn_orig():
        return 1
      if inner_fn==null:
        inner_fn = inner_fn_orig
      return fn() + 3
    

    Then "real" uses will get the right inner function, and in your tests you can provide your own.

    fn_to_test() # calls the real inner function
    def my_inner_fn():
      return 3
    fn_to_test( inner_fn=my_inner_fn ) # calls the new version
    

    You could also do this:

    def fn_to_test():
      def inner_fn_orign():
        return 1
      inner_fn = inner_fn_orig
      try:
        inner_fn = fn_to_test.inner_fn
      excecpt AttributeError:
        pass
      return inner_fn() + 3
    

    This way you just define the override:

    fn_to_test() # calls the real inner function
    def my_inner_fn():
      return 3
    fn_to_test.inner_fn = my_inner_fn
    fn_to_test() # calls the new version
    

提交回复
热议问题