Any tool to help unit testing? - phpunit

Im using phpunit. But you know its difficulties, no possibility to mock private functions, to access private variables, etc. Is there a tool which help me? Something to turn private functions to public, turn static method to mockable, etc

Not directly answering your question, but the best "tool" for making phpunit easier is good design of your code. If you are not sure what the good design would be for a given problem, you are already using the other good tool available to you - this site.
The things that you mention in your question as causing difficulties are generally difficult because there are issues with the design of your code. If it is hard to test, it will be hard to refactor, use, and maintain. The tests show you this early in your coding process and allow you to make changes to save your future self from issues.
For example in the difficulties from your question:
Mocking private functions - This is a smell that there is a second
class that needs to be created. Your object may be violating the
Single Responsibility Principle. This function should probably be
moved into its own object and passed in to system under test.
Access private variables - PHPUnit does have assertions for object
attributes (assertAttributeEquals, etc.). However this really
isn't something that you should need to use. A private variable is
an implementation detail of your object, there should be some sort of
public method that you can use to verify that the proper information
was set (a getter or dependency injected mock object)
Mocking static methods - There are many questions on SO about this
difficulty and many resources saying how static methods are not good
design. If you need to mock a static method, that means that you are
affecting global state. Static methods are also hiding dependencies
from users of your object and make things difficult to modify. Your
design becomes less flexible and more modular.

Yo do not need to test private methods and attributes. They're private for a reason and have sense only when called from inside the class that holds them. More, if you test a public method, you are also indirectly testing the private methods that it calls, and the result of the public function also might depend on some private attributes, which you are also testing with the public method.
If you test all public methods of a class (i.e. its interface), and by this I mean full code/branch coverage on those methods, then you are testing all private methods/attributes that are needed. If after testing all public stuff you are left with some pieces of code that wasn't reached, then you can safely delete that code, as it's of no use.

Related

How can we mock private methods without using power mockito

Can we mock private methods without using powermockito. I know it is possible though powermockito but just wanted to check with all, is it possible by some other means.
Thanks
-Sam
By design, this isn't possible without PowerMockito or a similar tool.
See Mockito's Wiki where they give the following reasons:
It requires hacking of classloaders that is never bullet proof and it
changes the API (you must use custom test runner, annotate the class,
etc.).
It is very easy to work around - just change the visibility of
method from private to package-protected (or protected).
It requires
the team to spend time implementing & maintaining it. And it does not
make sense given point (2) and a fact that it is already implemented
in different tool (powermock).
Finally... Mocking private methods is a
hint that there is something wrong with Object Oriented understanding.
In OO you want objects (or roles) to collaborate, not methods. Forget
about pascal & procedural code. Think in objects.
There are of course cases where it is not possible to work around, but just take a step back and
Make sure that you are testing the correct things (should you be testing private methods instead of the public ones)
Consider just changing these methods to be package private instead of relying on PowerMock.
Yes we can use the Reflection API for this which provided by Java vendor.

testable code vs static methods? (Moq)

I am seraching information about to test methods and Moq it's a good alternative, but it can't mock static methods.
However, is a question in this forums, I read that static methods are more efficients (consume less resources) than the non static method. Also, if a method does not use particular data of the object, it's a better option the static method. The question was in this post.
But if the method is static I can't mock the method, so it's seems that in some cases must choose between to be able to test the method or the performance of the static method.
There are some free alternative to moq to test static methods?
Thanks so much.
I do not know of a framework that can mock static methods because I do not believe it's possible except through something like assembly injection (i.e. emulate the assembly, namespace, and class so the method resolves to the injected symbol).
However, I need to ask, do you have code that needs to be so performant that sensitive to the minimal costs from calling an instance method? I highly doubt that's the case, and if it is, you shouldn't be using an environment that can pause your code for many milliseconds to perform a garbage collection. If that is the case, I'd love to know what kind of software you're writing :)
So if your code is not being used in high-frequency trading software, then consider if you'd rather have tested code or extremely marginally more performant code. This reeks to me of premature optimization...

Approach to “Template” a Set of VB.Net Classes to Ensure a Set of Similar Shared Functions Are Implemented

I have a series of classes that have a number of analogous Shared methods that I want to ensure are implemented in a consistent manner in each class. These Shared methods are called via reflection in various areas of code, and up to this point I’ve been keeping them in synch manually. As the number of classes grows, ensuring synchronization is becoming a bit tedious – as is the process to ensure, when I add a new Shared method to the paradigm, that it is indeed implemented in all of the classes to prevent run-time errors when reflection comes looking for them.
I’d initially thought this would be an ideal use of interfaces, but per various threads (such as Why we can not have Shared(static) function/methods in an interface/abstract class?) you cannot define Shared methods as part of an interface. I then tried to define a common base class and mark these methods MustOverride, but you cannot do that either. I’ve looked into delegates (which I’ve not used before), but it appears to allow the opposite of what I’m trying to do (namely, delegates seem to allow a common implementation of a common need from multiple classes instead of a unique implementation of a common need from multiple classes).
As such, is there an approach in VB.Net to ensure at compile-time that each of my classes implements a set of common Shared methods and functions in a consistent manner?
As a side note, the classes in question are currently all extensions of Entity Framework classes and are being blended into the EF classes.
EDIT: As a alternative to a language feature (which may not exist), I'd also be open to suggestions on any refactoring-type tools that provide this sort of functionality.
Here is sort of the skeleton of code I'm using:
Public MustInherit Class AbstractUpdateItem
Public MustOverride Function ValidateFields(ByRef dto As BusinessDTO) As Boolean
End Class
Public Class UpdateSomeFields
Inherits AbstractUpdateItem
Public Overrides Function ValidateFields(ByRef dto As BusinessDTO) As Boolean
' some code here to do the real stuff
End Function
End Class
When I comment out one of my Overrides Function (ValidateFields), I get a compile time error: Class x must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s): ValidateFields. So that would seem to ensure that they implement a set of methods. They aren't declared as shared, but will that do what you want?

Access Modifiers ... Why?

Ok so I was just thinking to myself why do programmers stress so much when it comes down to Access Modifiers within OOP.
Lets take this code for example / PHP!
class StackOverflow
{
private var $web_address;
public function setWebAddress(){/*...*/}
}
Because web_address is private it cannot be changed by $object->web_address = 'w.e.', but the fact that that Variable will only ever change is if your programme does $object->web_address = 'w.e.';
If within my application I wanted a variable not to be changed, then I would make my application so that my programming does not have the code to change it, therefore it would never be changed ?
So my question is: What are the major rules and reasons in using private / protected / non-public entities
Because (ideally), a class should have two parts:
an interface exposed to the rest of the world, a manifest of how others can talk to it. Example in a filehandle class: String read(int bytes). Of course this has to be public, (one/the) main purpose of our class is to provide this functionality.
internal state, which noone but the instance itself should (have to) care about. Example in a filehandle class: private String buffer. This can and should be hidden from the rest of the world: They have no buisness with it, it's an implementation detail.
This is even done in language without access modifiers, e.g. Python - except that we don't force people to respect privacy (and remember, they can always use reflection anyway - encapsulation can never be 100% enforced) but prefix private members with _ to indicate "you shouldn't touch this; if you want to mess with it, do at your own risk".
Because you might not be the only developer in your project and the other developers might not know that they shouldn't change it. Or you might forget etc.
It makes it easy to spot (even the compiler can spot it) when you're doing something that someone has said would be a bad idea.
So my question is: What are the major rules and reasons in using private / protected / non-public entities
In Python, there are no access modifiers.
So the reasons are actually language-specific. You might want to update your question slightly to reflect this.
It's a fairly common question about Python. Many programmers from Java or C++ (or other) backgrounds like to think deeply about this. When they learn Python, there's really no deep thinking. The operating principle is
We're all adults here
It's not clear who -- precisely -- the access modifiers help. In Lakos' book, Large-Scale Software Design, there's a long discussion of "protected", since the semantics of protected make subclasses and client interfaces a bit murky.
http://www.amazon.com/Large-Scale-Software-Design-John-Lakos/dp/0201633620
Access modifiers is a tool for defensive programming strategy. You protect your code consciously against your own stupid errors (when you forget something after a while, didn't understand something correctly or just haven't had enough coffee).
You keep yourself from accidentally executing $object->web_address = 'w.e.';. This might seem unnecessary at the moment, but it won't be unnecessary if
two month later you want to change something in the project (and forgot all about the fact that web_address should not be changed directly) or
your project has many thousand lines of code and you simply cannot remember which field you are "allowed" to set directly and which ones require a setter method.
Just because a class has "something" doesn't mean it should expose that something. The class should implement its contract/interface/whatever you want to call it, but in doing so it could easily have all kinds of internal members/methods that don't need to be (and by all rights shouldn't be) known outside of that class.
Sure, you could write the rest of your application to just deal with it anyway, but that's not really considered good design.

Any way to automatically generate QSharedData-based structures?

Qt has a build-in supprt for creating objects with integrated reference counting via QSharedData and QSharedDataPointer. All works great, but for each such object I need to write a lot of code: QSharedData-based implementation class with constructor and copy constructor, object class itsef with accessor methods for each filed.
For a simple structures with 5-10 fields this requires really lot of near same code. Is it some ways to automate such classes generation? Maybe it's some generators exists that take a short description and automatically generates implementation class and object class with all accessors?
You usually don't have to implement copy ctor or operator= when using QSharedData/Pointer. The default impls copy/assign the QSharedData-derived member, which usually does the Right Thing (TM).
For the public class, you need to implement the ctor creating the private object, and if the private class is not declared in the header but in the implementation (which is better), a dtor (doing nothing, the only point is that is not inlined and defined in the .cpp, after the private declaration).
For the private class, no method/ctor/dtor implementations are necessary.
For simple value-based classes, writing setters is of course tedious, but the same is true if you use plain private member variables. The overhead in LOC doesn't grow with the number of members.
And no, there is no standard generator solution for that I know of, although writing a script or emacs macro etc. doing it is not that hard. Probably would make sense to add such things to a publicly available toolbox, or QtCreator...
I don't think generators would exist for these things, but I suggest two things:
(ab)use existing shared containers (QVector, QList...)
read the documentation (with examples) on QSharedData, QSharedDataPointer, and QExplicitelySharedDataPointer
The two subclasses have simple examples that show how to implement the shared-ness it seems. I can't help you further though, because I've never had the need to create my own.
On second thought, why not make all data fields public, and use the QSharedData derivative as a struct-like class with reference counting? Maybe not nice on encapsulation, but if you're careful, nothing wrong should happen.

Resources