testable code vs static methods? (Moq) - 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...

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.

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.

Write Unit Tests for Static Methods

In my project there are lots of Static methods and all are inturn hitting the DB. I am supposed to write Unit Test for the project but often struck with as all the methods are static and they are hitting DB. Is there any way to overcome this. Sorry for being abstract in the question but my concern is what is the way to write unit test for static methods and those hitting DB. MOQ is not useful when the methods are static and also in my project one method is calling other method within the same class. So in this case i cannot MOQ the inside method as both are in the same class.
The project I'm currently in is lot worse than what you have described. It is a blue print of an un-testable system. There are couple of options I think, but it all depends on your situation.
Write Integration test, which hits the database, and test multiple components together. I know this is not ideal, but it at least give some confidence on the work you do. Then try to refactor your code in a small step at a time, (be sure to take baby steps) and write Unit tests around that code. Make sure your integration tests continue to pass. You are still allowed to refactor your intergeneration type tests, if the semantics are changed.
This might not be easier as I said, and it takes time. That's why I said it is depends on your situation.
Another option would be (I know many people do this with legacy code) to use one of those pricey Isolation frameworks such as Isolator, MS Fakes perhaps to fake out those un testable dependencies. Once those tests written you can look at re factoring the code to make it more testable.

Would you consider this a singleton/singleton pattern?

Imagine in the Global.asax.cs file I had an instance class as a private field. Let's say like this:
private MyClass _myClass = new MyClass();
And I had a static method on Global called GetMyClass() that gets the current HttpApplication and returns that instance.
public static MyClass GetMyClass()
{
return ((Global)HttpContext.Current.ApplicationInstance)._myClass;
}
So I could get the instance on the current requests httpapplication by calling Global.GetMyClass().
Keep in mind that there is more than one (Global) HttpApplication. There is an HttpApplication for each request and they are pooled/shared, so in the truest sense it is not a real singleton. But it does follow the pattern to a degree.
So as the question asked, would you consider this at the very least the singleton pattern?
Would you say it should not be used? Would you discourage its use? Would you say it's a possibly bad practice like a true singleton.
Could you see any problems that may arise from this type of usage scenario?
Or would you say it's not a true singleton, so it's OK, and not bad practice. Would you recommend this as a semi-quasi singleton where an instance per request is required? If not what other pattern/suggestion would you use/give?
Have you ever used anything such as this?
I have used this on past projects, but I am unsure if it's a practice I should stay away from. I have never had any issues in the past though.
Please give me your thoughts and opinions on this.
I am not asking what a singleton is. And I consider a singleton bad practice when used improperly which is in many many many cases. That is me. However, that is not what I am trying to discuss. I am trying to discuss THIS scenario I gave.
Whether or not this fits the cookie-cutter pattern of a Singleton, it still suffers from the same problems as Singleton:
It is a static, concrete reference and cannot be substituted for separate behavior or stubbed/mocked during a test
You cannot subclass this and preserve this behavior, so it's quite easy to circumvent the singleton nature of this example
I'm not a .NET person so I'll refrain from commenting on this, except for this part:
Would you say its bad practice like a true singleton.
True singletons aren't 'bad practice'. They're HORRIBLY OVERUSED but that's not the same thing. I read something recently (can't remember where, alas) where someone pointed out the -- 'want or need' vs. 'can'.
"We only want one of these", or "we'll only need one": not a singleton.
"We CAN only have one of these": singleton
That is, if the very idea of having two of that object will break something in horrible and subtle ways, yes, use a singleton. This is true a lot more rarely than people think, hence the proliferation of singletons.
A Singleton is an object, of which, there CAN BE only one.
Objects of which there just happens to be one right now are not singleton.
Since you're talking about a web application, you need to be very careful with assuming anything with static classes or this type of pseudo-singleton because as David B said, they are only shared across that thread. Where you will get in trouble is if IIS is configured to use more than one worker process (configured with the ill-named "Web-Garden" mode, but also the # worker processes can be set in machine.config). Assuming the box has more than one processor, whoever is trying to tweak it's performance is bound to turn this on.
A better pattern for this sort of thing is to use the HttpCache object. It is already thread-safe by nature, but what still catches most people is you object also needs to be thread-safe (since you're only going to probably create the instance and then read/write to a lot of its properties over time). Here's some skeleton code to give you an idea of what I'm talking about:
public SomeClassType SomeProperty
{
get
{
if (HttpContext.Current.Cache["SomeKey"] == null)
{
HttpContext.Current.Cache.Add("SomeKey", new SomeClass(), null,
System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromDays(1),
CacheItemPriority.NotRemovable, null);
}
return (SomeClassType) HttpContext.Current.Cache["SomeKey"];
}
}
Now if you think you might need a web farm (multi-server) scale path, then the above won't work as the application cache isn't shared across machines.
Forget singleton for a moment.
You have static methods that return application state. You better watch out.
If two threads access this shared state... boom. If you live on the webserver, your code will eventually be run in a multi-threaded context.
I would say that it is definitely NOT a singleton. Design patterns are most useful as definitions of common coding practices. When you talk about singletons, you are talking about an object where there is only one instance.
As you yourself have noted, there are multiple HttpApplications, so your code does not follow the design of a Singleton and does not have the same side-effects.
For example, one might use a singleton to update currency exchange rates. If this person unknowingly used your example, they would fire up seven instances to do the job that 'only one object' was meant to do.

What are the downsides to static methods?

What are the downsides to using static methods in a web site business layer versus instantiating a class and then calling a method on the class? What are the performance hits either way?
The performance differences will be negligible.
The downside of using a static method is that it becomes less testable. When dependencies are expressed in static method calls, you can't replace those dependencies with mocks/stubs. If all dependencies are expressed as interfaces, where the implementation is passed into the component, then you can use a mock/stub version of the component for unit tests, and then the real implementation (possibly hooked up with an IoC container) for the real deployment.
Jon Skeet is right--the performance difference would be insignificant...
Having said that, if you are building an enterprise application, I would suggest using the traditional tiered approach espoused by Microsoft and a number of other software companies. Let me briefly explain:
I'm going to use ASP.NET because I'm most familiar with it, but this should easily translate into any other technology you may be using.
The presentation layer of your application would be comprised of ASP.NET aspx pages for display and ASP.NET code-behinds for "process control." This is a fancy way of talking about what happens when I click submit. Do I go to another page? Is there validation? Do I need to save information to the database? Where do I go after that?
The process control is the liaison between the presentation layer and the business layer. This layer is broken up into two pieces (and this is where your question comes in). The most flexible way of building this layer is to have a set of business logic classes (e.g., PaymentProcessing, CustomerManagement, etc.) that have methods like ProcessPayment, DeleteCustomer, CreateAccount, etc. These would be static methods.
When the above methods get called from the process control layer, they would handle all the instantiation of business objects (e.g., Customer, Invoice, Payment, etc.) and apply the appropriate business rules.
Your business objects are what would handle all the database interaction with your data layer. That is, they know how to save the data they contain...this is similar to the MVC pattern.
So--what's the benefit of this? Well, you still get testability at multiple levels. You can test your UI, you can test the business process (by calling the business logic classes with the appropriate data), and you can test the business objects (by manually instantiating them and testing their methods. You also know that if your data model or objects change, your UI won't be impacted, and only your business logic classes will have to change. Also, if the business logic changes, you can change those classes without impacting the objects.
Hope this helps a bit.
Performance wise, using static methods avoids the overhead of object creation/destruction. This is usually non significant.
They should be used only where the action the method takes is not related to state, for instance, for factory methods. It'd make no sense to create an object instance just to instantiate another object instance :-)
String.Format(), the TryParse() and Parse() methods are all good examples of when a static method makes sense. They perform always the same thing, do not need state and are fairly common so instancing makes less sense.
On the other hand, using them when it does not make sense (for example, having to pass all the state into the method, say, with 10 arguments), makes everything more complicated, less maintainable, less readable and less testable as Jon says. I think it's not relevant if this is about business layer or anywhere else in the code, only use them sparingly and when the situation justifies them.
If the method uses static data, this will actually be shared amongst all users of your web application.
Code-only, no real problems beyond the usual issues with static methods in all systems.
Testability: static dependencies are less testable
Threading: you can have concurrency problems
Design: static variables are like global variables

Resources