How can we mock private methods without using power mockito - reflection

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.

Related

Any tool to help unit testing?

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.

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.

Why are getters prefixed with the word "get"?

Generally speaking, creating a fluid API is something that makes all programmers happy; Both for the creators who write the interface, and the consumers who program against it. Looking beyond conventions, why is it that we prefix all our getters with the word "get". Omitting it usually results in a more fluid, easy to read set of instructions, which ultimately leads to happiness (however small or passive). Consider this very simple example. (pseudo code)
Conventional:
person = new Person("Joey")
person.getName().toLower().print()
Alternative:
person = new Person("Joey")
person.name().toLower().print()
Of course this only applies to languages where getters/setters are the norm, but is not directed at any specific language. Were these conventions developed around technical limitations (disambiguation), or simply through the pursuit of a more explicit, intentional feeling type of interface, or perhaps this is just a case of trickle a down norm. What are your thoughts? And how would simple changes to these conventions impact your happiness / daily attitudes towards your craft (however minimal).
Thanks.
Because, in languages without Properties, name() is a function. Without some more information though, it's not necessarily specific about what it's doing (or what it's going to return).
Functions/Methods are also supposed to be Verbs because they are performing some action. name() obviously doesn't fit the bill because it tells you nothing about what action it is performing.
getName() lets you know without a doubt that the method is going to return a name.
In languages with Properties, the fact that something is a Property expresses the same meaning as having get or set attached to it. It merely makes things look a little neater.
The best answer I have ever heard for using the get/set prefixes is as such:
If you didn't use them, both the accessor and mutator (getter and setter) would have the same name; thus, they would be overloaded. Generally, you should only overload a method when each implementation of the method performs a similar function (but with different inputs).
In this case, you would have two methods with the same name that peformed very different functions, and that could be confusing to users of the API.
I always appreciate consistent get/set prefixing when working with a new API and its documentation. The automatic grouping of getters and setters when all functions are listed in their alphabetical order greatly helps to distinguish between simple data access and advanced functinality.
The same is true when using intellisense/auto completion within the IDE.
What about the case where a property is named after an verb?
object.action()
Does this get the type of action to be performed, or execute the action... Adding get/set/do removes the ambiguity which is always a good thing...
object.getAction()
object.setAction(action)
object.doAction()
In school we were taught to use get to distinguish methods from data structures. I never understood why the parens wouldn't be a tipoff. I'm of the personal opinion that overuse of get/set methods can be a horrendous time waster, and it's a phase I see a lot of object oriented programmers go through soon after they start.
I may not write much Objective-C, but since I learned it I've really come to love it's conventions. The very thing you are asking about is addressed by the language.
Here's a Smalltalk answer which I like most. One has to know a few rules about Smalltalk BTW.
fields are only accessible in the they are defined.If you dont write "accessors" you won't be able to do anything with them.
The convention there is having a Variable (let's anme it instVar1.
then you write a function instVar1 which just returns instVar1 and instVar: which sets
the value.
I like this convention much more than anything else. If you see a : somewhere you can bet it's some "setter" in one or the other way.
Custom.
Plus, in C++, if you return a reference, that provides potential information leakage into the class itself.

Use-cases for reflection

Recently I was talking to a co-worker about C++ and lamented that there was no way to take a string with the name of a class field and extract the field with that name; in other words, it lacks reflection. He gave me a baffled look and asked when anyone would ever need to do such a thing.
Off the top of my head I didn't have a good answer for him, other than "hey, I need to do it right now". So I sat down and came up with a list of some of the things I've actually done with reflection in various languages. Unfortunately, most of my examples come from my web programming in Python, and I was hoping that the people here would have more examples. Here's the list I came up with:
Given a config file with lines like
x = "Hello World!"
y = 5.0
dynamically set the fields of some config object equal to the values in that file. (This was what I wished I could do in C++, but actually couldn't do.)
When sorting a list of objects, sort based on an arbitrary attribute given that attribute's name from a config file or web request.
When writing software that uses a network protocol, reflection lets you call methods based on string values from that protocol. For example, I wrote an IRC bot that would translate
!some_command arg1 arg2
into a method call actions.some_command(arg1, arg2) and print whatever that function returned back to the IRC channel.
When using Python's __getattr__ function (which is sort of like method_missing in Ruby/Smalltalk) I was working with a class with a whole lot of statistics, such as late_total. For every statistic, I wanted to be able to add _percent to get that statistic as a percentage of the total things I was counting (for example, stats.late_total_percent). Reflection made this very easy.
So can anyone here give any examples from their own programming experiences of times when reflection has been helpful? The next time a co-worker asks me why I'd "ever want to do something like that" I'd like to be more prepared.
I can list following usage for reflection:
Late binding
Security (introspect code for security reasons)
Code analysis
Dynamic typing (duck typing is not possible without reflection)
Metaprogramming
Some real-world usages of reflection from my personal experience:
Developed plugin system based on reflection
Used aspect-oriented programming model
Performed static code analysis
Used various Dependency Injection frameworks
...
Reflection is good thing :)
I've used reflection to get current method information for exceptions, logging, etc.
string src = MethodInfo.GetCurrentMethod().ToString();
string msg = "Big Mistake";
Exception newEx = new Exception(msg, ex);
newEx.Source = src;
instead of
string src = "MyMethod";
string msg = "Big MistakeA";
Exception newEx = new Exception(msg, ex);
newEx.Source = src;
It's just easier for copy/paste inheritance and code generation.
I'm in a situation now where I have a stream of XML coming in over the wire and I need to instantiate an Entity object that will populate itself from elements in the stream. It's easier to use reflection to figure out which Entity object can handle which XML element than to write a gigantic, maintenance-nightmare conditional statement. There's clearly a dependency between the XML schema and how I structure and name my objects, but I control both so it's not a big problem.
There are lot's of times you want to dynamically instantiate and work with objects where the type isn't known until runtime. For example with OR-mappers or in a plugin architecture. Mocking frameworks use it, if you want to write a logging-library and dynamically want to examine type and properties of exceptions.
If I think a bit longer I can probably come up with more examples.
I find reflection very useful if the input data (like xml) has a complex structure which is easily mapped to object-instances or i need some kind of "is a" relationship between the instances.
As reflection is relatively easy in java, I sometimes use it for simple data (key-value maps) where I have a small fixed set of keys. One one hand it's simple to determine if a key is valid (if the class has a setter setKey(String data)), on the other hand i can change the type of the (textual) input data and hide the transformation (e.g simple cast to int in getKey()), so the rest of the application can rely on correctly typed data.
If the type of some key-value-pair changes for one object (e.g. form int to float), i only have to change it in the data-object and its users but don't have to keep in mind to check the parser too. This might not be a sensible approach, if performance is an issue...
Writing dispatchers. Twisted uses python's reflective capabilities to dispatch XML-RPC and SOAP calls. RMI uses Java's reflection api for dispatch.
Command line parsing. Building up a config object based on the command line parameters that are passed in.
When writing unit tests, it can be helpful to use reflection, though mostly I've used this to bypass access modifiers (Java).
I've used reflection in C# when there was some internal or private method in the framework or a third party library that I wanted to access.
(Disclaimer: It's not necessarily a best-practice because private and internal methods may be changed in later versions. But it worked for what I needed.)
Well, in statically-typed languages, you'd want to use reflection any time you need to do something "dynamic". It comes in handy for tooling purposes (scanning the members of an object). In Java it's used in JMX and dynamic proxies quite a bit. And there are tons of one-off cases where it's really the only way to go (pretty much anytime you need to do something the compiler won't let you do).
I generally use reflection for debugging. Reflection can more easily and more accurately display the objects within the system than an assortment of print statements. In many languages that have first-class functions, you can even invoke the functions of the object without writing special code.
There is, however, a way to do what you want(ed). Use a hashtable. Store the fields keyed against the field name.
If you really wanted to, you could then create standard Get/Set functions, or create macros that do it on the fly. #define GetX() Get("X") sort of thing.
You could even implement your own imperfect reflection that way.
For the advanced user, if you can compile the code, it may be possible to enable debug output generation and use that to perform reflection.

Resources