So I am learning TDD using the many resources here on SO, but I just cant seem to figure out what I do with private/protected objects instantiated inside a given method/constructor. Lets say I have a connection string. That connection string is used to construct a Sqlcommand or Sqlhelper. Well I want to mock that Sqlhelper so that when I test other methods I don't have to rely on the results coming from my database. But I cant access the Sqlhelper.
How do I work around this?
Its generally best (except for a very few rare occasions) to test only the public interface of the class as a whole. Try not to use one of the workaround methods (such as private objects) unless you really have to. Accessing private members of classes in tests tends to look good at first as theres less code to write to test an object, however when things start to change (and they will) anything accessing the internals of a class makes it more difficult to change its implementation, this can be crippling to a project if most of the tests are written in this way.
In this particular case you are interacting with an external dependency outside of your control (i.e. SqlHelper), I'd recommend wrapping the SqlHelper object in your own object that implements an ISqlHelper interface (or a more reasonably named interface for your scenario).
e.g.
public interface ISqlHelperWrapper
{
void ExecuteQuery();
}
Then inject this in through the constructor of you're object under test:
public class SqlConsumer
{
private ISqlHelperWrapper _sqlHelper;
public SqlConsumer(ISqlHelperWrapper helper)
{
this._sqlHelper = helper;
}
public void QuerySomething()
{
this._sqlHelper.ExecuteQuery();
}
}
Not only is this a better design (you've isolated the sql implementation specific stuff from the SqlConsumer, and given it fewer reasons to change). But you can now mock the ISqlHelper instance using a mocking framework as well as switch the implementation on construction.
Given your connectionstring scenario above, you could initialise the sqlhelperwrapper (There are better names for this) with the connectionstring and your SqlConsumer object doesn't need to know about it.
Related
At my workplace there seems to currently be a crusade against static classes. I can understand part of that, they do sort of break the whole unit testing modularity thing. However, I am seeing an influx of code reviews that call for removing static classes.
A common case is a utility class this is spring-injected with a few other objects that are "known" at compile-time. It has no other member variables. If class M is calling this static class, I always see the suggestion to make this utility class non-static and inject it into class M.
This doesn't make sense to me. I don't particularly see anything wrong with it other than that it seems a waste of time and makes utility class less easily usable. As far as I can tell the justification is usually for unit testing, but I don't like the idea that valid code has to be changed to conform to a testing paradigm. Admittedly mocking a simple static utility class would probably be overkill.
Are static classes appropriate in this use case, or best avoided?
I think the differences in the two approaches are small, but as long as the class contain no state it is slightly better to make it static. Let's say I have this code in class A:
StaticClass.utilMethod()
If I want to use this code in class B I can copy and paste. That's it. No adding member variables, injection, etc. cmd-c cmd-v.
Considering your existing code uses static classes and modifying that will take work, it's definitely best to continue using static classes.
I vote for using the static classes... i.e. A class with just static methods for purely Utility purposes. Even java has provided us such classes like java.util.Collections and java.util.Arrays
If you pretend for a moment that your static class did not belong to you, that it was, say, part of the .NET framework, how would your team handle it? Their answer would be my answer. In other words, if their answer to that question is inconsistent with what they're asking you to do, then they should probably either change how they work with .NET static classes or with how they work with yours.
I avoid using static classes (assuming we are actually talking about classes that contain static methods), and I do it for the sake of testability.
If you are using static methods, you will have a difficult time mocking/stubbing the portion of your code that uses said static for your unit tests.
Consider this:
public String myMethod() {
String complicatedStringOutput = MyUtility.createComplicatedStringOutput();
//do some more complicated work on this String
}
To write a unit test for this method, how would you go about making it a 'true unit test' without needing to also test the creation of complicatedStringOutput? In my unit tests, I prefer to test only the method that is the focus of the unit test.
Change it to this:
public String myMethod(MyNonStaticUtility util) {
String complicatedStringOutput = util.createComplicatedStringOutput();
//do some more complicated work on this String
}
Suddenly, this class is much easier to write a 'true unit test' for. You can control the behavior of MyNonStaticUtility by either using a stub or mock.
All that said, it is really up to you (or your Business Unit). If you value unit tests and feel that it is important to have good test coverage of your complicated code, this is the preferred approach. If you do not have time/money to invest in 'fixing' your code, then it just won't happen.
Depends, naturally.
How do you want to test the code that uses the static classes?
Do the static classes encapsulate behavior you'll need to mock often?
Will anybody ever need to modify the behavior of those static classes?
Finally:
Is there a compelling reason not to inject a Spring-managed singleton bean?
Admittedly mocking a simple static utility class would probably be overkill.
You're absolutely right on this. Static classes should only be used for utility classes that are extremely simple, where there is no benefit of mocking such a class. If you're using them for any other purpose, you should rethink your design.
Is it reasonable to use a non-static class if that class does not contain state?
This really has nothing to do with state. For example, strategy objects often contain no state, yet they are not static; they usually implement a common interface and need to be interchangeable / mockable.
I'm trying to use TDD when writing a class that needs to parse an XML document. Let's say the class is called XMLParser, and its constructor takes in a string for the path to the XML file to parse. I would like to have a Load() method that tries to load this XML into memory, and performs a few checks on the file such as file system errors, whether or not its an XML file, etc.
My question is about alternatives: I've read that it's bad practice to have private methods that you need to test, and that you should be able to just test the public interface and let the private methods do their thing. But in this case, this functionality is pretty important, and I don't think it should be public.
Does anyone have good advice for a scenario like this?
I suggest to redesign your architecture a bit. Currently, you have one high level class with low level functionality embedded. Split that into multiple classes that belong to different layers (I use the term "layer" very loosely here).
Example:
Have one class with the public interface of your current class. (-> High level layer)
Have one class responsible for loading files from disk and handling IO errors (-> Low level layer)
Have one class responsible for validating XML documents (-> Inbetween)
Now you can test all three of these classes independently!
You will see that your high level class will do not much more than just composing the two lower level classes.
Use no access modifier (which is the next up to private) and write the test in the same package.
Good OOD is important but for really important functionality testing is more important. Good practices are always only a guideline and they are good in the general scenario.
You could also try to encapsulate that specific file-checking behaviour in another object and have your parser instantiate it and use it. This is probably what I would do. In this way you could also even use this functionality somewhere else with minimal effort.
You can make a subclass as part of your test package that exposes public accessors to the private methods (which should then be protected).
Public class TestableClass : MyClass
{
public someReturnType TestMethod() {
return base.PrivateMethod();
}
}
In the below snip I have my controller which takes three interfaces. These are wired up via Ninject. Ok all great, definately a step in the right direction. My questions are this?
1.) Would it be better to wrap the 3 interfaces up in to one interface and a implement that way, thus reducing the amount of params passed to the ctor of the controller?
2.) Leave it alone, it is working?
I am always looking for ways to abstract the hell out of everything..
Thoughts?
public class RegistrationController : Controller
{
private readonly ICategoriesService _categoriesService;
private readonly IAuthenticationService _authenticationService;
private readonly IRegistrationService _registrationService;
// Ctor
public RegistrationController(ICategoriesService categoriesService,
IAuthenticationService authenticationService,
IRegistrationService registrationService)
{
_categoriesService = categoriesService;
_authenticationService = authenticationService;
_registrationService = registrationService;
}
}
Having a huge interface (or a huge class, which is what you'll need in order to implement a huge interface) because it is "convenient" is widely considered an antipattern. Based on the names of your current interfaces, they seem to be nicely and logically structured around what kind of operations they provide, and I suggest that you keep them that way (this also gives higher flexibility, since there may be other places where you only need some of the interfaces).
By the way: If you have proper unit tests and integration tests, "leave it alone, it's working" is a phrase that is never needed. ;-)
When you add a new method to a class where do you put it? At the end of the class...the top? Do you organize methods into specific groupings? Sorted alphabetically?
Just looking for general practices in keeping class methods organized.
Update When grouped where do you add the new method in the group? Just tack on the end or do you use some sort of sub-grouping, sorting?
Update 2 Mmmm...guess the question isn't as clear as I thought. I'm not really looking for class organization. I'm specifically interested in adding a new method to an existing class. For example:
public class Attendant
{
public void GetDrinks(){}
public void WelcomeGuests(){}
public void PickUpTrask(){}
public void StrapIn(){}
}
Now we're going to add a new method PrepareForCrash(). Where does it go? At the top of the list, bottom, alphabetically or near the StrapIn() method since it's related.
Near "StrapIn" because it's related. That way if you refactor later, all related code is nearby.
Most code editors allow you to browse method names alphabetically in another pane, so organizing your code functionally makes sense within the actual code itself. Group functional methods together, makes life easier when navigating through the class.
For goodness sake, not alphabetically!
I tend to group my functions in the order I expect them to be called during the life of the object, so that a top to bottom read of the header file tends to explain the operation of the class.
I think it's a personal choice.
However I like to organise my classes as such.
public class classname
{
<member variables>
<constructors>
<destructor>
<public methods>
<protected methods>
<private methods>
}
The reason for this is as such.
Member variables at the top
To see what member variables exist and if they are initialised.
Constructors
To see if the member variables are setup/initialised as well as what are all the construction options for the class.
Destructor
To see the how the class is cleaned up and verify it with the constructors and member variables.
Public methods
To see what are the available contracts callers of the object can use.
Protected methods
To see what inherited classes would be using.
Private methods
As it's information about the internals of the class if you needed to know about the internals you can just scroll straight to the end quickly. But to know the interface for the class it's all at the start.
UPDATE - Based on OP's update
Logically a good way would be to organise the methods by categories of what they do.
This way you get the readabilty of categorising your methods as well as the alphabetical search from you IDE (provided this is in your IDE).
However in a practical sense I think placing the methods at the end of that section is the best way. It would be quite hard to continually police where each method goes, as it's subjective, for every method if the code is shared by more than yourself.
If you were to make this a standard it'd be quite hard to provide the boundaries for where to put each method.
What I like about C# and VB.net is the ability to use #region tags, so generally my classes look like this
class MyClass
{
#region Constructors
public MyClass()
{
}
public MyClass(int x)
{
_x = x;
}
#endregion
#region Members
private int _x;
#endregion
#region methods
public void DoSomething()
{
}
#endregion
#region Properties
public int Y {get; private set;}
#endregion
}
So basically You put similar things together so you can collapse everything to definition and get to your stuff really faster.
Generally, it depends on the existing grouping; if there's an existing grouping that the new method fits into, I'll put it there. For example, if there's a grouping of operators, I'll put the new method with the operators if it's an operator.
Of course, if there is no good grouping, adding a method may suggest a new grouping; I treat that as an opportunity for refactoring, and try to regroup the existing operators where reasonable.
I organize all methods into regions like public methods, private methods or sometimes by features like Saving methods, etc..
IMHO:
If you organize your methods alphabetically, put a new one depends on its name. Otherwise put it at the bottom of related group. This helps to know, what method is newer. The bigger problem is how to organize methods in groups, e.g. depend on what properties, but this is more individual for everyone and depends on a specific class.
I have repository class that is used by at least 2 other classes. This repository class needs to be initialized - which is high in cost (querying database). Now, I create separate instances of repository wherever I need it. The thing is, that everytime I create repository it has to be initialized. How to design such repository to be TDD-friendly? The first thing in my mind was Singleton but it's not the solution.
I hope by TDD-friendly you mean 'testable' code. For a Singleton ObjectX, I think the most common way is to split the responsibility (SRP) of 'controlling creation' to another class so ObjectX does all the things it is supposed to do.
Then you have another class ObjectXFactory or Host or whatever you wanna call it that is responsible for providing a single instance for all clients (and providing thread sync if needed and so on)
Object X can be TDDed independently. You can create a new instance in your test case and test functionality.
ObjectXFactory on the other hand is also easy to test.. you just need to see if multiple GetInstance() calls return the same object. OR better delegate this responsibility to an IOC framework like Spring, which lets you declaratively mark an object definition to obtain singleton behavior (Saving you the effort of writing tests as well)
You just need to educate and conform to a Team convention that ObjectX constructor is not to be called - always use ObjectXFactory.CreateInstance(). (If you find that you have a awareness/discipline problem, mark ObjectX's ctor as internal and visible to only to the test assembly via the sneaky InternalsVisibleToAttribute)
HTH
One answer for the TDD part is learn mocking.
Check out this excellent article by Stephen Walther:
http://stephenwalther.com/blog/archive/2008/03/23/tdd-introduction-to-rhino-mocks.aspx
Do you use any type of IOC container? Unity is my container of choice, and it contains a ContainerControledLifetimeManager which makes your class a singleton, but not managed by yourself.
Consider caching instances for performance improvement before you consider singletons. But for TDD friendly designs consider strategy injection so that 'slow' bits can be removed for testing and replaced with stubs and mocks. Try not to do db calls in tests if you can.
You can't do that -- at least not in a true TDD sense.
Relying on DI/IoC strategies such as Unity means your tests are dependent on an external component and are not tested in isolation.
The tests then become integration tests, not unit tests.
==Ignore the answer below here==
I guess you wanted to know how to make Repository testable.
Introducing an interface for it would allow you to mock or stub it, which will in turn make sure that you can test your objects independent of any concrete implementation of Repository.
I'll illustrate this using Rhino Mocks 3.5 for .NET 3.5:
Let's make an interface out of Repository, let's call that IRepository
public interface IRepository
{
}
Now, since you need to use IRepository for two different objects, then let's just use generics so you can instantiate your repository with that:
public interface IRepository<T>
of course that would mean that you would have some sort of find method:
{
public IEnumerable<T> Find(Criteria criteria)
}
where your criteria object is some object that allows you to set what to look for, e.g., your where clause.
Now, you have your object:
public class SomeObject
{
IRepository<SomeObject> repository;
public SomeObject(){}
public IRepository<SomeObject> repository { get; set; }
IEnumerable<SomeObject> FindAll()
{
//let's assume new Criteria() will return all results
return respository.Find(new Criteria());
}
}
You want to to test SomeObject such that FindAll() will return an expected set of results -- this is where Rhino Mocks would come in:
[TestFixture]
public class SomeObjectTests
{
[Test]
public void TestSomeObjectFindAll()
{
IRepository<SomeObject> stubRepository = MockRepsitory.GenerateStub<IRepsitory<SomeObject>>();
stubRepository.Expect(r => r.Find(new Criteria())
.Return(new List<SomeObject>{
new SomeObject(),
new SomeObject(),
new SomeObject());
var testObject = new SomeObject { Repository = stubRepository };
IList<SomeObject> findAllResult = testObject.FindAll();
//returned list contains 3 elements, as expected above
Assert.AreEqual(3, findAllResult.Count)
}
}
Note that the code above is not TDD best practice in all respects, but it's a place to start.
Key concept here is introducing interfaces to allow for loose coupling of objects, especially when the object tends to do things like access databases, file systems, etc.
There is a more comprehensive example and better examples on Ben Hall's article on Rhino Mocks.