Mocking method results

前端 未结 6 1580
情歌与酒
情歌与酒 2021-02-08 16:00

I\'m trying to find a way to fake the result of a method called from within another method.

I have a \"LoadData\" method which calls a separate helper to get some data a

6条回答
  •  醉话见心
    2021-02-08 16:49

    You have a problem there. I don't know if thats a simplified scenario of your code, but if the Helper class is used that way, then your code is not testable. First, the Helper class is used directly, so you can't replace it with a mock. Second, you're calling a static method. I don't know about C#, but in Java you can't override static methods.

    You'll have to do some refactoring to be able to inject a mock object with a dummy GetSomeData() method.

    In this simplified version of your code is difficult to give you a straight answer. You have some options:

    • Create an interface for the Helper class and provide a way for the client to inject the Helper implementation to the MyClass class. But if Helper is just really a utility class it doesn't make much sense.
    • Create a protected method in MyClass called getSomeData and make it only call Helper.LoadSomeData. Then replace the call to Helper.LoadSomeData in LoadData with for getSomeData. Now you can mock the getSomeData method to return the dummy value.

    Beware of simply creating an interface to Helper class and inject it via method. This can expose implementation details. Why a client should provide an implementation of a utility class to call a simple operation? This will increase the complexity of MyClass clients.

提交回复
热议问题