Stubbing & mocking in PHPUnit in a Zend Framework application - zend-framework

I am new to the Zend Framework and PHPUnit. I am transforming a legacy application to a MVC architecture and am trying to write unit tests. I am somewhat familiar with unit testing concepts but am stuck with stubbing and mocking in general. For instance consider the following
In a controller action I am trying to test I pass in a member ID. I then initialize a member object using the ID. Then I call a number of methods associated with the member object and assign the return values to the view objects.
class A extends Zend_Controller_Action {
public function viewAction() {
$member = new Member($this->getRequest()-> getParam('id'));
//perform various calls on the member object
$gender = $member->getGender();
...
//assign the return values to the view object
$this->view->assign('gender',$gender);
...
}
}
How do I mock the $member variable in my tests so that I can customize the methods return values?
If my understanding here is incorrect I would greatly appreciate some guidance.
Thank you!

If I understand you correctly, you're writing a test for this action. In that case it's impossible to mock $member since the new instance is created inside the method. That's why we're all striving to float as many of our new statements as far up in the object graph as possible (DI).
Generally there is the special PHPunit testcase Zend_Test_PHPUnit to test your controllers.
But it is, as a matter of fact, very hard or even impossible to test ZF controllers correctly (meaning with full isolation). You'd be better of to test the rest of your app, your general library, etc.
In other words, in the ZF1 logic, the controller is the central wiring place (after the bootstrap), where a lot of new statements are traditionally used. Obviously that leads to non-testability because every instance which is created instead of injected, is unmockable.
As #vascowhite pointed out, it is also generally good to strive for lean controllers. This means, move as much logic as possible to your model layer. This will lead to less redundance (DRY) and better testability at the same time.
But pay attention not to bloat your models either. At one point you will probably want to factor some code out into additional components.
An additional problem is that you can't mock the Front Controller either since it's a singleton. So you really don't have many options to test such an action. The only option would be to inject the member instance or get it from the registry (not a good idea either).
So, given all that it is clear that you can't reach full isolation for your action tests. But
ZF2 will be much easier to test, though.

You'd better start with covering controllers with functional tests. In this case you can bypass this mocking problem and get better coverage of test. Controllers are always hard to be covered with unit tests, because they are strongly coupled.
To write functional tests with ZF consider using Codeception: http://codeception.com/01-27-2012/bdd-with-zend-framework.html
Also, there are some examples, how a unit tests for controller can be made. But, sincerly, I recommend unit-testing controllers after functional tests for them are made.
http://codeception.com/docs/06-UnitTestsAndBDD#TestingController

Related

Static method and constructor interception mocking in Scala/Spark

All, Here is a problem that my searches have yielded little insight into. I think this should be a fairly common problem for all of us developing against big data frameworks but also seek 100% test coverage. So I will post the question here in an attempt to gather the best community response & ideas.
Consider the scenario where we need to mock a class that instantiate an external API object
class SolrClientWrapper {
def doWork() = {
val cli = new CloudSolrClient("zkHost1")
???
}
}
To get 100% test coverage, and without actually relying on the Solr server to be up at all times during unit testing, we shall have a way to intercept the call to new CloudSolrClient. As far as I know, the ONLY library available is PowerMock
Here is The Twist
PowerMock and other Mock libraries require asm as a dependency, but a complex framework Spark project also require asm. There are version conflicts and thus (test-)runtime hell.
What is the best design refactor/libraries for this situation?
Instead of creating a new CloudSolrClient object within the SolrClientWrapper class, it should be passed as a dependency. Then in your test you can pass a mock instead of the real object. Note that there are many dependency injection frameworks and mechanisms that can make it easier for you to manage your dependencies (e.g. to automatically instantiate them and pass to the constructor for you).
Not sure what asm is, but the code you posted should be easily testable without such dependencies once you remove parts of the code that instantiate stuff inside the class body (and thus the need to "intercept" anything).

coffeescript and repetition of code. Is there a solution?

So - I am really really digging coffeescript. But, I am curious how the possibility of repetition of code is dealth with across a large repository of code.
For instance.
Lets say I create a simple class.
class Cart
constructor: (#session, #group) ->
class Shoes extends Cart
compiler will create __extends and __hasProp methods.
Mind you, this is just one example -- pretty much this happens with loops etc... So, granted each bit of code is usually in its walled garden.. BUT, there could be many many of the same methods thru-out a code base.... because of the compiler just creating generic helper methods that are all the same.
Anyone else have to contend with this or deal with that possible bloat?
That is probably a lot more specific to what build tool you are using to manage a large codebase. grunt-contrib-coffee for example provides the ability to concatenate before compilation which means something like the __extends method should only get declared once. Likewise, I believe, asset pipeline in rails makes similar optimizations through the require statements.

Passing HttpFileCollectionBase to the Business Layer - Bad?

hopefully there's an easy solution to this one.
I have my MVC2 project which allows uploads of files on certain forms. I'm trying to keep my controllers lean, and handle the processing within the business layer of this sort of thing.
That said, HttpFileCollectionBase is obviously in the System.Web assembly.
Ideally I want to call to something like:
UserService.SaveEvidenceFiles(MyUser user, HttpFileCollectionBase files);
or something similar and have my business layer handle the logic of how and where these things are saved.
But, it feels a little icky to have my models layer with a reference to System.Web in terms of separation of concerns etc.
So, we have (that I'm aware of) a few options:
the web project handling this, and my controllers getting fatter
mapping the HttpFileCollectionBase to something my business layer likes
passing the collection through, and accepting that I reference System.Web from my business project
Would love some feedback here on best practice approaches to this sort of thing - even if not specifically within the context of the above.
I'd just use a custom model binder if you want to keep the logic out of your controllers - then you can stick the extracted data into the model which you can do what you want with.
http://www.heartysoft.com/post/2010/05/06/ASPNET-MVC-ModelBinding-Multiple-File-Uploads-to-an-Array.aspx
Clarification - I consider model binders and other interception techniques to be a convenient way of splitting logic out of controllers and into separately maintainable containers - this is infrastructure code/web logic and thus does not belong in the business logic and thus can reference System.Web etc happily.
Clarification - Effectively this is your Option 2 in disguise, you use model binders to map the unfriendly data into something the rest of your code can recognise, but you do it in a way that doesn't compromise your clean controllers.
assuming you can't easily mock up HttpFileCollectionBase you could pass in something like Dictionary<String, MyFile> where MyFile wraps HttpPostedFile. if HttpFileCollectionBase can easily be mockable for unit tests i see no point.

Do Extension Methods Hide Dependencies?

All,
Wanted to get a few thoughts on this. Lately I am becoming more and more of a subscriber of "purist" DI/IOC principles when designing/developing. Part of this (a big part) involves making sure there is little coupling between my classes, and that their dependencies are resolved via the constructor (there are certainly other ways of managing this, but you get the idea).
My basic premise is that extension methods violate the principles of DI/IOC.
I created the following extension method that I use to ensure that the strings inserted into database tables are truncated to the right size:
public static class StringExtensions
{
public static string TruncateToSize(this string input, int maxLength)
{
int lengthToUse = maxLength;
if (input.Length < maxLength)
{
lengthToUse = input.Length;
}
return input.Substring(0, lengthToUse);
}
}
I can then call my string from within another class like so:
string myString = "myValue.TruncateThisPartPlease.";
myString.TruncateToSize(8);
A fair translation of this without using an extension method would be:
string myString = "myValue.TruncateThisPartPlease.";
StaticStringUtil.TruncateToSize(myString, 8);
Any class that uses either of the above examples could not be tested independently of the class that contains the TruncateToSize method (TypeMock aside). If I were not using an extension method, and I did not want to create a static dependency, it would look more like:
string myString = "myValue.TruncateThisPartPlease.";
_stringUtil.TruncateToSize(myString, 8);
In the last example, the _stringUtil dependency would be resolved via the constructor and the class could be tested with no dependency on the actual TruncateToSize method's class (it could be easily mocked).
From my perspective, the first two examples rely on static dependencies (one explicit, one hidden), while the second inverts the dependency and provides reduced coupling and better testability.
So does the use of extension methods conflict with DI/IOC principles? If you're a subscriber of IOC methodology, do you avoid using extension methods?
I think it's fine - because it's not like TruncateToSize is a realistically replaceable component. It's a method which will only ever need to do a single thing.
You don't need to be able to mock out everything - just services which either disrupt unit testing (file access etc) or ones which you want to test in terms of genuine dependencies. If you were using it to perform authentication or something like that, it would be a very different matter... but just doing a straight string operation which has absolutely no configurability, different implementation options etc - there's no point in viewing that as a dependency in the normal sense.
To put it another way: if TruncateToSize were a genuine member of String, would you even think twice about using it? Do you try to mock out integer arithmetic as well, introducing IInt32Adder etc? Of course not. This is just the same, it's only that you happen to be supplying the implementation. Unit test the heck out of TruncateToSize and don't worry about it.
I see where you are coming from, however, if you are trying to mock out the functionality of an extension method, I believe you are using them incorrectly. Extension methods should be used to perform a task that would simply be inconvenient syntactically without them. Your TruncateToLength is a good example.
Testing TruncateToLength would not involve mocking it out, it would simply involve the creation of a few strings and testing that the method actually returned the proper value.
On the other hand, if you have code in your data layer contained in extension methods that is accessing your data store, then yes, you have a problem and testing is going to become an issue.
I typically only use extension methods in order to provide syntactic sugar for small, simple operations.
Extension methods, partial classes and dynamic objects. I really like them, however you must tread carefully , there be monsters here.
I would take a look at dynamic languages and see how they cope with these sort of problems on a day to day basis, its really enlightening. Especially when they have nothing to stop them from doing stupid things apart from good design and discipline. Everything is dynamic at run time, the only thing to stop them is the computer throwing a major run time error. "Duck Typing" is the maddest thing I have ever seen, good code is down to good program design, respect for others in your team, and the trust that every member, although have the ability to do some wacky things choose not to because good design leads to better results.
As for your test scenario with mock objects/ICO/DI, would you really put some heavy duty work in an extension method or just some simple static stuff that operate in a functional type way? I tend to use them like you would in a functional programming style, input goes in, results come out with no magic in the middle, just straight up framework classes that you know the guys at MS have designed and tested :P that you can rely on.
If your are doing some heavy lifting stuff using extension methods I would look at your program design again, check out your CRC designs, Class models, Use Cases, DFD's, action diagrams or whatever you like to use and figure out where in this design you planned to put this stuff in an extension method instead of a proper class.
At the end of the day, you can only test against your system design and not code outside of your scope. If you going to use extension classes, my advice would be to look at Object Composition models instead and use inheritance only when there is a very good reason.
Object Composition always wins out with me as they produce solid code. You can plug them in, take them out and do what you like with them. Mind you this all depends on whether you use Interfaces or not as part of your design. Also if you use Composition classes, the class hierarchy tree gets flattened into discrete classes and there are fewer places where your extension method will be picked up through inherited classes.
If you must use a class that acts upon another class as is the case with extension methods, look at the visitor pattern first and decide if its a better route.
Its a pain because they are hard to mock. I usually use one of these strategies
Yep, scrap the extension its a PITA to mock out
Use the extension and just test that it did the right thing. i.e. pass data into the truncate and check it got truncated
If it's not some trivial thing, and I HAVE to mock it, I'll make my extension class have a setter for the service it uses, and set that in the test code.
i.e.
static class TruncateExtensions{
public ITruncateService Service {private get;set;}
public string TruncateToSize(string s, int size)
{
return (Service ?? Service = new MyDefaultTranslationServiceImpl()). TruncateToSize(s, size);
}
}
This is a bit scary because someone might set the service when they shouldn't, but I'm a little cavalier sometimes, and if it was really important, I could do something clever with #if TEST flags, or the ServiceLocator pattern to avoid the setter being used in production.

Encapsulation in the age of frameworks

At my old C++ job, we always took great care in encapsulating member variables, and only exposing them as properties when absolutely necessary. We'd have really specific constructors that made sure you fully constructed the object before using it.
These days, with ORM frameworks, dependency-injection, serialization, etc., it seems like you're better off just relying on the default constructor and exposing everything about your class in properties, so that you can inject things, or build and populate objects more dynamically.
In C#, it's been taken one step further with Object initializers, which give you the ability to basically define your own constructor. (I know object initializers are not really custom constructors, but I hope you get my point.)
Are there any general concerns with this direction? It seems like encapsulation is starting to become less important in favor of convenience.
EDIT: I know you can still carefully encapsulate members, but I just feel like when you're trying to crank out some classes, you either have to sit and carefully think about how to encapsulate each member, or just expose it as a property, and worry about how it is initialized later. It just seems like the easiest approach these days is to expose things as properties, and not be so careful. Maybe I'm just flat wrong, but that's just been my experience, espeically with the new C# language features.
I disagree with your conclusion. There are many good ways of encapsulating in c# with all the above mentioned technologies, as to maintain good software coding practices. I would also say that it depends on whose technology demo you're looking at, but in the end it comes down to reducing the state-space of your objects so that you can make sure they hold their invariants at all times.
Take object relational frameworks; most of them allow you to specify how they are going to hydrate the entities; NHibernate for example allows you so say access="property" or access="field.camelcase" and similar. This allows you to encapsulate your properties.
Dependency injection works on the other types you have, mostly those which are not entities, even though you can combine AOP+ORM+IOC in some very nice ways to improve the state of these things. IoC is often used from layers above your domain entities if you're building a data-driven application, which I guess you are, since you're talking about ORMs.
They ("they" being application and domain services and other intrinsic classes to the program) expose their dependencies but in fact can be encapsulated and tested in even better isolation than previously since the paradigms of design-by-contract/design-by-interface which you often use when mocking dependencies in mock-based testing (in conjunction with IoC), will move you towards class-as-component "semantics". I mean: every class, when built using the above, will be better encapsulated.
Updated for urig: This holds true for both exposing concrete dependencies and exposing interfaces. First about interfaces: What I was hinting at above was that services and other applications classes which have dependencies, can with OOP depend on contracts/interfaces rather than specific implementations. In C/C++ and older languages there wasn't the interface and abstract classes can only go so far. Interfaces allow you to tie different runtime instances to the same interface without having to worry about leaking internal state which is what you're trying to get away from when abstracting and encapsulating. With abstract classes you can still provide a class implementation, just that you can't instantiate it, but inheritors still need to know about the invariants in your implementation and that can mess up state.
Secondly, about concrete classes as properties: you have to be wary about what types of types ;) you expose as properties. Say you have a List in your instance; then don't expose IList as the property; this will probably leak and you can't guarantee that consumers of the interface don't add things or remove things which you depend on; instead expose something like IEnumerable and return a copy of the List, or even better, do it as a method:
public IEnumerable MyCollection { get { return _List.Enum(); } } and you can be 100% certain to get both the performance and the encapsulation. Noone can add or remove to that IEnumerable and you still don't have to perform a costly array copy. The corresponding helper method:
static class Ext {
public static IEnumerable<T> Enum<T>(this IEnumerable<T> inner) {
foreach (var item in inner) yield return item;
}
}
So while you can't get 100% encapsulation in say creating overloaded equals operators/method you can get close with your public interfaces.
You can also use the new features of .Net 4.0 built on Spec# to verify the contracts I talked about above.
Serialization will always be there and has been for a long time. Previously, before the internet-area it was used for saving your object graph to disk for later retrieval, now it's used in web services, in copy-semantics and when passing data to e.g. a browser. This doesn't necessarily break encapsulation if you put a few [NonSerialized] attributes or the equivalents on the correct fields.
Object initializers aren't the same as constructors, they are just a way of collapsing a few lines of code. Values/instances in the {} will not be assigned until all of your constructors have run, so in principle it's just the same as not using object initializers.
I guess, what you have to watch out for is deviating from the good principles you've learnt from your previous job and make sure you are keeping your domain objects filled with business logic encapsulated behind good interfaces and ditto for your service-layer.
Private members are still incredibly important. Controlling access to internal object data is always good, and shouldn't be ignored.
Many times private methods I've found to be overkill. Most of the time, if the work you're doing is important enough to break out, you can refactor it in such a way that either a) the private method is trivial, or b) is an integral part of other functions.
In addition, with unit testing, having many methods private makes it very hard to unit test. There are ways around that (making test objects friends, etc), but add difficulties.
I wouldn't discount private methods entirely though. Any time there's important, internal algorithms that really make no sense outside of the class there's no reason to expose those methods.
I think that encapsulation is still important, it helps more in libraries than anything imho. You can create a library that does X, but you don't need everyone to know how X was created. And if you wanted to create it more specifically to obfuscate the way you create X. The way I learned about encapsulation, I remember also that you should always define your variables as private to protect them from a data attack. To protect against a hacker breaking your code and accessing variables that they are not supposed to use.