Writing/implementing an API: testability vs information hiding

后端 未结 6 1223
春和景丽
春和景丽 2021-01-21 12:56

Many times I am involved in the design/implementation of APIs I am facing this dilemma.

I am a very strong supporter of information hiding and try to use various techniq

6条回答
  •  耶瑟儿~
    2021-01-21 13:17

    My go-to answer for this type of thing is a "test proxy". In your test package, derive a subclass from your system under test, which contains "pass-through" accessors to protected data.

    Advantages:

    • You can directly test, or mock, methods you don't want made public.
    • Since the test proxy lives in the test package, you can ensure it is never used in production code.
    • A test proxy requires far fewer changes to code in order to make it testable than if you were testing the class directly.

    Disadvantages:

    • The class must be inheritable (no final)
    • Any hidden members you need to access cannot be private; protected is the best you can do.
    • This isn't strictly TDD; TDD would lend itself to patterns that didn't require a test proxy in the first place.
    • This isn't strictly even unit testing, because at some level you are dependent on the "integration" between the proxy and the actual SUT.

    In short, this should normally be a rarity. I tend to use it only for UI elements, where best practice (and default behavior of many IDEs) is to declare nested UI controls as inaccessible from outside the class. Definitely a good idea, so you can control how callers get data from the UI, but that also makes it difficult to give the control some known values to test that logic.

提交回复
热议问题