Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static methods and unit tests

I've been reading that static methods tend to be avoided when using TDD because they tend to be hard to mock. I find though, that the easiest thing to unit test is a static method that has simple functionality. Don't have to instantiate any classes, encourages methods that a simple, do one thing, are "standalone" etc.

Can someone explain this discrepancy between TDD best practices and pragmatic ease?

thanks, A

like image 327
anderl.heckmaier Avatar asked Nov 18 '10 23:11

anderl.heckmaier


People also ask

Can I mock static class in unit test?

The powerful capabilities of the feature-rich JustMock framework allow you to mock static classes and calls to static members like methods and properties, set expectations and verify results. This feature is a part of the fastest, most flexible and complete mocking tool for crafting unit tests.

What are static methods?

A static method (or static function) is a method defined as a member of an object but is accessible directly from an API object's constructor, rather than from an object instance created via the constructor.

What is the difference between a method and a static method?

Static method means which will exist as a single copy for a class. But instance methods exist as multiple copies depending on the number of instances created for that class.


1 Answers

A static method is easy to test, but something that directly calls a static method generally is not easy to test independent of the static method it depends on. With a non-static method you can use a stub/mock/fake instance to ease testing, but if the code you're testing calls static methods it's effectively "hard-wired" to that static method.

like image 141
Laurence Gonsalves Avatar answered Sep 19 '22 19:09

Laurence Gonsalves