I’ve got a question about a unit test that I’m writing. I have a method called “execute()” in a component which I am testing. In the method I do this:
var httpService = new http();
Is the only way to mock the new http() call, to write a new method in the component which returns a new http object and then mock that new method that I created? Or is there an easier way to mock it? I’ve looked around but haven’t come up with an alternative.
There are a number ways you can do this, and the more common is the mock of the object. But this means tougher adherence to your code, which will teach you greater refactoring skills.
In this case, you could write a service that was entirely for HTTP calls, in which you can then mock the entire object as you would normally. Thus your code would then be changed to use a getHTTPService() in your method, which can then be mocked as a method.
If you feel that a service for one call is overkill, remember the service can do other things like convert to json, or whatever etc., the thing is that this is just an example. But if you do feel this is overkill, then just move the http into its own method in the component so you can then mock that method only.
Hopefully that might help…
That is correct. You would want to do this anyway, that is part of what unit testing exposes, where you have coupling in your application. It forces you to have methods only do their intended purpose and not much else so you can test them in isolation.
Thanks Guys, I figured that would be the solution