Question

I have this injection metadata at the top of a model:

<cfproperty name="injector" inject="wirebox" />

and later, in a function I request a dependency and start using it:

variables.injector.getInstance("MyTransientDependency").doSomeStuff()

In writing my unit test I want to mock the MyTransientDependency object, but I'm not sure how to go about it, whereas it's provided by wirebox.

To give a more real-world example, let's say wirebox has getInstance() called on it multiple times within the same function, with different names passed in each time. So mocking the return of the getInstance function would be a pain, and (if something like $results() were used) a maintenance nightmare if the order the dependencies were internally requested in changed without changing the behavior of the function in a way that would require updating the unit test. That approach just feels icky anyway.

I'm guessing there's a straightforward way to hijack the variables.injector reference and give my component a wirebox instance (or something like it) that will return the mocks I specify in my unit test rather than the actual objects mapped in my app's binder (Wirebox.cfc)... and do it based on the names passed in to the getInstance() function within the code I'm testing.

Where that gets a bit tricky is if within a single function you want to test you get multiple instances of the same named object on which you need to mock the same function to return different results (like the function you test needs 2 'person' objects and initializes one to be a person of type A and the other to be a person of type B and the person component is expected to return differently structured data from a particular function you need to mock. In such a case you may not be able to get away from using something like $results(), and maybe that's what it's there for.

But my main issue is what is the 'right way' to mock transients?

Was it helpful?

Solution

Dang. A little more searching in the docs and I found it.

http://wiki.coldbox.org/wiki/MockBox.cfm#.24args() outlines the use of $args() to mock the result of the combination of a function and a specific argument (or set of args).

For an example of use, see the getWireBox function in this example code: https://groups.google.com/forum/#!msg/coldbox/FoXPjEf798g/rVKhN-8VY34J

We mock wirebox and then use $args() to mock the getInstance function when different values are passed in.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top