TDD in C++. How to test friend functions of private class? - c++

if I have a class with a helper (private member) class within it, like this
class Obj;
class Helper {
friend class Obj;
private:
int m_count;
Helper(){ m_count = 0;}; // Note this is a private constructor
void incrementCount(){
++m_count;
};
};
class Obj {
Helper *m_pHelper;
// note that this is a private getter
int getHelperCount() { return m_pHelper->m_count; };
// the public API starts here
public:
Obj() { m_pHelper = new Helper(); };
void incrementCount(){ m_pHelper->incrementCount(); };
};
So how may I TDD such a system?
auto obj = new Obj();
obj->incrementCount();
// what to assert???
That is my question and the following is just some background.
Response to some answers and comments.
If noone outside the class should be interested, then your tests should not be interested either. – Arne Mertz
If nobody is interested in the value outside the class, why are you – utnapistim
Even if no one outside needs the value, I may still want to know that if it's set correctly, as it is used by other self contained internal method of the class that use that value. Maybe the value is the speed where the controller will use it to update the model. Or maybe it's the position where the view will use it to draw something on the screen. And in fact all other components of Obj would be able to access that variable. It may be a bad design issue, and in this case I would like to know what better alternatives I can have. The design is listed in the background section at the bottom of this post.
define private public - Marson Mao
Love this ingenious abuse of keywords haha. But may not be concluded as the best solution just yet.
You need to "expose" the friendship relation in the header of your class. Thus you have to acknowledge there the existence of a class used to test yours.
If you use the pImpl idiom, you could make the members of the pImpl itself all public, the pImpl itself private and give your unit tests access to the pImpl - CashCow
Does this mean that I should friend the test in my original class? Or add extra "test" methods to it?
I just started TDD very recently. Is it common (or better is it good) to intrude the original class with test class dependency? I don't think I have the appropriate knowledge to judge. Any advice on this?
Miscellaneous: AFAIK TDD is not just writing test, but instead a development process. I have read that I should only write tests to the public interface. But the problem is, like the situation in question, most of the codes etc are contained within private class. How may I use TDD to create these codes?
Background
FYI if you would like to know why I am making a private class:
I am developing a game from cocos2dx. The game engine adopts a Node tree structure for the updates, rendering etc and every game object would inherit from a Node class provided in the engine. Now I want to implement the MVC pattern on a game object. So for each object I basically created a Object class with 3 helper classes corresponding to each of the MVC components named ObjectModel, ObjectView, ObjectController. Theoretically no one should access the MVC classes directly and would only be accessed somehow through the Object class so I make the 3 of them private. The reason of making the MVC components explicitly as classes is because the View and Controller are updating at different rates (more specifically the Controller performs frame dependent updates, while the View do a simple interpolation based on the model data). The Model class is created purely for religious reasons lol.
Thanks in advance.

How to test friend functions of private class?
Thou shalt not!
A class (or module or library or whatever) exposes a public interface for a reason. You have the public interface (which is geared for client use, so it has invariants, preconditions, postconditions, side-effects, whatever - which can and should be tested) and implementation details, that allow you to implement the public interface, easier.
The point of having a private implementation, is that you are allowed to change it as you please, without affecting other code (without affecting even tests). All tests should pass after you change your private implementation, and client (and test) code should (by design) not care at all that you changed the private implementation.
So how may I TDD such a system?
TDD your public interface only. Testing implementation details means you end up coding to an implementation, instead of an interface.
Regarding your comment:
The problem is I don't even have a getter in the public interface. So how can my test check that the value is 0 or 1? And the getter is intentionally made private as no one should be interested in the value outside the class
If nobody is interested in the value outside the class, why are you (i.e. why would you wish to test for it?)

The #define private public trick can have side effects with the way some compiler are mangling function symbols (Visual c++ compiler is including access specifier in its name mangling)
You can also change visibility with the using statement :
struct ObjTest : public Obj
{
using Obj::incrementCount;
}
But like other people said, try to not test private stuff if possible.

I have encounter such problem when I was writing unit test as well.
After some searching I decided the most effective way is to add this in your Test.cpp:
#define private public
NOTE: add this before your desired include file, maybe your Obj.h, for example.
I think this method looks crazy but it's actually reasonable, because this #define only affect your test file, so all other people using your Obj.h is totally fine.
Some reference:
Unit testing of private methods

I vote, as #Marson Mao says, for #define private public.
If you want to control what to make private or public a bit more, you can do this in yourtests.cpp
#define private public
#include "IWantAccessViolationForThis.h"
#undef private
#include "NormalFile.h"
This way you can have a bit more control and try to do this trick in as few places as possible.
Another nice property of this approach is that it is non-intrusive, meaning that you don't need to clutter your real implementation and header files with #ifdefs for testing and not testing modes.

Your friend has full access to the class that it is a friend of. This might be done for many reasons and one of those could well be for unit-testing purpose, i.e. you want to be able to write a unit test that can call private members of the class and check the internal variables show what you would expect them to show, but you do not want that to be part of the public API.
You need to "expose" the friendship relation in the header of your class. Thus you have to acknowledge there the existence of a class used to test yours. No worries, you develop in the real world and classes are tested.
In order to write a unit test you will want to implement that class to provide protected member functions (probably static ones) that call all the relevant private functions or get the private members, and then you write classes that derive from yours. Note that those will not have direct access as friendship is not inherited, thus the static protected members.
If you use the pImpl idiom, you could make the members of the pImpl itself all public, the pImpl itself private and give your unit tests access to the pImpl (through the same model as above). This is now simpler as you only need to create one method for your "tester".
With regards to data members of a class, in recent years I have been known to put all these into a struct, i.e. have them all public, and then for the class to have a private instance of that struct. It can be easier for handling this kind of thing, and also serialisation / factories to your class, where they can create the struct which is all public, then construct your class from it.

Related

Testing through inherited class using protected members

Let us assume that you've got a class in C++, for example with an internal state machine that is hard to test. Assume that you have a proper architecture with mocks for all classes used by the class under test. The class under test has some public interface and some non-public internal implementation.
You want to properly unit test this class. In order to make sure that all parts of it work correctly you would like to create some example conditions that you would not allow through the public interface. However, you want to test whether, under these circumstances, the system reacts correctly or not.
One possibility would be to make your member variables protected, so that an inherited class, specifically created for unit testing, is able to extend the public interface to control those variables during testing. You could then, for example, set the system to a certain state, set some internal variables and make sure that e.g. the state transition is according to your requirements.
From a design point of view: Is it justifiable to make non-public members protected in order to be able to get them more testable? What are your opinions? Are there better alternative design decisions?
I had a similar issue. To be honest , I don't see a point why you should not also test the private part of a class.
My solution to this was using the pre-compiler only for the private statement.
#ifndef UNITTEST
private:
#endif // UNITTEST
Of course we could argue now, that I am manipulating the original class itself and I am not any longer testing properly in real conditions , but if you are testing one class and not several within this one unit test I see no issue.
This question about the protected is a bit like the question about making methods virtual for the sake of mocking. You have to decide case by case.

Is it wrong to extend class in order to unit test it's protected property?

I had to make a fix, where the line of code was removed for the second time. So I decided to write a unit test just for that.
A Class in its constructor sets a property that I want to test. This property happens to be protected so I can't access it in the unit test.
[Test]
public void Constructor_WhenCalled_ThenSomePropertyIsPopulated()
{
var vm= new SomeViewModel();
//line below doesn't compile as SomeProperty is protected
Assert.IsNotNull(vm.SomeProperty);
So I decided, in my unit test file, to extend that class (it wasn't sealed) and expose the protected property as a public getter:
public class SomeViewModelExtended : SomeViewModel
{
public SomeViewModelExtended() : base() { }
public new object SomeProperty
{
get { return base.SomeProperty; }
}
}
//now I can test
[Test]
public void Constructor_WhenCalled_ThenSomePropertyIsPopulated()
{
var vm= new SomeViewModelExtended();
Assert.IsNotNull(vm.SomeProperty);
Now there's an argument on my team that I should only be testing public interfaces among other things and that this is a total quick and dirty hack.
But isn't one of the purposes of unit tests to preserve the code base from unwanted changes? If this is totally wrong what else should do?
A protected variable is part of the interface. It's part of the interface that any sub class can use. This question has a good summary on protected variables. Is it good practice to make member variables protected?
If you allow derived classes access to their base class' data, then derived classes need to take care to not to invalidate the base class' data's invariants. That throws encapsulation out of the window and is just wrong. (So do getters and setters, BTW.)
In answer to your question, if the variable should not be accessed by sub classes then it should be private. Otherwise your unit test is valid and arguably it should have been implemented earlier!
After reading the Roy Osherove's 'Art of Unit Testing' my opinion on this is that testing + maintainability are primary use cases for good code. As such I feel the case for extending types to help with testing is more than valid.
Of course if you can design a type to not require it then that's good, but maintainability and thus testability are paramount.
Often it's said the leaky abstractions are a bad choice, however I find in most cases this is because these two primary use cases are not being considered. An abstraction should be good for all users: functionality & testing & maintenance.
You should remove the field altogether until it is actually needed to pass an external test. If there is no external behavior that fails, you don't need the field.
Since the field is protected, I assume that you created it to have something derive from it. Does this derived class need the protected field in order to pass any of its tests? In that case, you're covered.

Is it possible in Qt to unit test (access) private methods?

I'm writing unit tests for my app, and now I've stumbled on a class in which I should test private methods. This could be result of poor design of particular class, but I must do it. Is there any way in Qt to call private methods, maybe using QMetaObject or something similar ?
For unit testing I am using QTestLib framework.
The proper (read annoying) answer is that you should not be testing private methods, those are implementation details ;-).
OTOH -- have you thought about conditionally declaring them protected/private depending on whether you are in testing or no and then extending? I've used that to get me out of a similar pinch in the past.
#ifdef TESTING
// or maybe even public!
#define ACCESS protected
#else
#define ACCESS private
#endif
/* your class here */
class Foo {
ACCESS
int fooeyness;
}
// or better yet, place this in a different file!
#ifdef TESTING
/*
class which extends the tested class which has public accessors
*/
#endif
Solution 1, quick and easy: make the test class(es) a friend of the public one.
class Foo {
// ...
private:
friend class FooTest;
};
This way your FooTest class can access all members of the public class. However, this way you need to modify the original class every time you want to access private data from a different test, and you leak information about the tests in the public API, and you possibly open up for class naming conflicts (what if there's /another/ FooTest class around?), and so on.
Solution 2, aka properly done: don't put private methods in the public class, but make a private class with public methods.
class Foo {
//
private:
friend class FooPrivate;
FooPrivate *d;
};
FooPrivate gets declared in its own header, which may not be installed, or stay in a include-privates/ subdirectory, or whatever -- i.e. it stays out of the way for normal usage. The public class stays clean this way.
class FooPrivate {
public:
// only public stuff in here;
// and especially this:
static FooPrivate *get(Foo *f) { return f->d; }
};
The test then includes the private header and calls FooPrivate::get(fooObj) to get the private class instance and then happily uses it.
I disagree with the "private members are implementation details" mentality, in my mind that roughly translates to "test only part of your code".
I can related to "units are units" argument, but why not try to cover as much of your code with tests as possible, even inside units? Aka. giving your units a thorough rectal examination.
And with this image in mind, one approach that I have been using frequently that is not mentioned in the other answers is to do the following:
Always declare members you want to test as protected in stead of private in your code.
Subclass your class in the testcode and simply make the selectors you need or simply write the test-code directly as members in that sub-class's implementation.
NOTE: You have to be careful with classes that rely on complex instantiation patterns to ensure that you construct them correctly (read: call the original class' constructor from the subclass ctor).
I have found more convenient way to do this. First, all private methods should be private slots.
Then you create an instance of the class:
Foo a;
Then we can use QMetaObject::invokeMethod to call any slot that method has (public or private). So if we want to call method Test, we can do it like this:
QMetaObject::invokeMethod(&a, "Test", Qt::DirectConnection);
Also, we can have return value and send arguments ... Actually, everything is answered here: http://doc.qt.nokia.com/stable/qmetaobject.html#invokeMethod
I've once read that Unit Test should test the class public interface, and not the protected/private stuff.
Your class should just behave right from outside. If implementation strategy changes, your Unit Test class is still the same.

How to write jUnit tests for private methods [duplicate]

How do I use JUnit to test a class that has internal private methods, fields or nested classes?
It seems bad to change the access modifier for a method just to be able to run a test.
If you have somewhat of a legacy Java application, and you're not allowed to change the visibility of your methods, the best way to test private methods is to use reflection.
Internally we're using helpers to get/set private and private static variables as well as invoke private and private static methods. The following patterns will let you do pretty much anything related to the private methods and fields. Of course, you can't change private static final variables through reflection.
Method method = TargetClass.getDeclaredMethod(methodName, argClasses);
method.setAccessible(true);
return method.invoke(targetObject, argObjects);
And for fields:
Field field = TargetClass.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(object, value);
Notes:
TargetClass.getDeclaredMethod(methodName, argClasses) lets you look into private methods. The same thing applies for
getDeclaredField.
The setAccessible(true) is required to play around with privates.
The best way to test a private method is via another public method. If this cannot be done, then one of the following conditions is true:
The private method is dead code
There is a design smell near the class that you are testing
The method that you are trying to test should not be private
When I have private methods in a class that are sufficiently complicated that I feel the need to test the private methods directly, that is a code smell: my class is too complicated.
My usual approach to addressing such issues is to tease out a new class that contains the interesting bits. Often, this method and the fields it interacts with, and maybe another method or two can be extracted in to a new class.
The new class exposes these methods as 'public', so they're accessible for unit testing. The new and old classes are now both simpler than the original class, which is great for me (I need to keep things simple, or I get lost!).
Note that I'm not suggesting that people create classes without using their brain! The point here is to use the forces of unit testing to help you find good new classes.
I have used reflection to do this for Java in the past, and in my opinion it was a big mistake.
Strictly speaking, you should not be writing unit tests that directly test private methods. What you should be testing is the public contract that the class has with other objects; you should never directly test an object's internals. If another developer wants to make a small internal change to the class, which doesn't affect the classes public contract, he/she then has to modify your reflection based test to ensure that it works. If you do this repeatedly throughout a project, unit tests then stop being a useful measurement of code health, and start to become a hindrance to development, and an annoyance to the development team.
What I recommend doing instead is using a code coverage tool, such as Cobertura, to ensure that the unit tests you write provide decent coverage of the code in private methods. That way, you indirectly test what the private methods are doing, and maintain a higher level of agility.
From this article: Testing Private Methods with JUnit and SuiteRunner (Bill Venners), you basically have 4 options:
Don't test private methods.
Give the methods package access.
Use a nested test class.
Use reflection.
Generally a unit test is intended to exercise the public interface of a class or unit. Therefore, private methods are implementation detail that you would not expect to test explicitly.
Just two examples of where I would want to test a private method:
Decryption routines - I would not
want to make them visible to anyone to see just for
the sake of testing, else anyone can
use them to decrypt. But they are
intrinsic to the code, complicated,
and need to always work (the obvious exception is reflection which can be used to view even private methods in most cases, when SecurityManager is not configured to prevent this).
Creating an SDK for community
consumption. Here public takes on a
wholly different meaning, since this
is code that the whole world may see
(not just internal to my application). I put
code into private methods if I don't
want the SDK users to see it - I
don't see this as code smell, merely
as how SDK programming works. But of
course I still need to test my
private methods, and they are where
the functionality of my SDK actually
lives.
I understand the idea of only testing the "contract". But I don't see one can advocate actually not testing code—your mileage may vary.
So my trade-off involves complicating the JUnit tests with reflection, rather than compromising my security and SDK.
The private methods are called by a public method, so the inputs to your public methods should also test private methods that are called by those public methods. When a public method fails, then that could be a failure in the private method.
In the Spring Framework you can test private methods using this method:
ReflectionTestUtils.invokeMethod()
For example:
ReflectionTestUtils.invokeMethod(TestClazz, "createTest", "input data");
Another approach I have used is to change a private method to package private or protected then complement it with the #VisibleForTesting annotation of the Google Guava library.
This will tell anybody using this method to take caution and not access it directly even in a package. Also a test class need not be in same package physically, but in the same package under the test folder.
For example, if a method to be tested is in src/main/java/mypackage/MyClass.java then your test call should be placed in src/test/java/mypackage/MyClassTest.java. That way, you got access to the test method in your test class.
To test legacy code with large and quirky classes, it is often very helpful to be able to test the one private (or public) method I'm writing right now.
I use the junitx.util.PrivateAccessor-package for Java. It has lots of helpful one-liners for accessing private methods and private fields.
import junitx.util.PrivateAccessor;
PrivateAccessor.setField(myObjectReference, "myCrucialButHardToReachPrivateField", myNewValue);
PrivateAccessor.invoke(myObjectReference, "privateMethodName", java.lang.Class[] parameterTypes, java.lang.Object[] args);
Having tried Cem Catikkas' solution using reflection for Java, I'd have to say his was a more elegant solution than I have described here. However, if you're looking for an alternative to using reflection, and have access to the source you're testing, this will still be an option.
There is possible merit in testing private methods of a class, particularly with test-driven development, where you would like to design small tests before you write any code.
Creating a test with access to private members and methods can test areas of code which are difficult to target specifically with access only to public methods. If a public method has several steps involved, it can consist of several private methods, which can then be tested individually.
Advantages:
Can test to a finer granularity
Disadvantages:
Test code must reside in the same
file as source code, which can be
more difficult to maintain
Similarly with .class output files, they must remain within the same package as declared in source code
However, if continuous testing requires this method, it may be a signal that the private methods should be extracted, which could be tested in the traditional, public way.
Here is a convoluted example of how this would work:
// Import statements and package declarations
public class ClassToTest
{
private int decrement(int toDecrement) {
toDecrement--;
return toDecrement;
}
// Constructor and the rest of the class
public static class StaticInnerTest extends TestCase
{
public StaticInnerTest(){
super();
}
public void testDecrement(){
int number = 10;
ClassToTest toTest= new ClassToTest();
int decremented = toTest.decrement(number);
assertEquals(9, decremented);
}
public static void main(String[] args) {
junit.textui.TestRunner.run(StaticInnerTest.class);
}
}
}
The inner class would be compiled to ClassToTest$StaticInnerTest.
See also: Java Tip 106: Static inner classes for fun and profit
As others have said... don't test private methods directly. Here are a few thoughts:
Keep all methods small and focused (easy to test, easy to find what is wrong)
Use code coverage tools. I like Cobertura (oh happy day, it looks like a new version is out!)
Run the code coverage on the unit tests. If you see that methods are not fully tested add to the tests to get the coverage up. Aim for 100% code coverage, but realize that you probably won't get it.
If using Spring, ReflectionTestUtils provides some handy tools that help out here with minimal effort. For example, to set up a mock on a private member without being forced to add an undesirable public setter:
ReflectionTestUtils.setField(theClass, "theUnsettableField", theMockObject);
Private methods are consumed by public ones. Otherwise, they're dead code. That's why you test the public method, asserting the expected results of the public method and thereby, the private methods it consumes.
Testing private methods should be tested by debugging before running your unit tests on public methods.
They may also be debugged using test-driven development, debugging your unit tests until all your assertions are met.
I personally believe it is better to create classes using TDD; creating the public method stubs, then generating unit tests with all the assertions defined in advance, so the expected outcome of the method is determined before you code it. This way, you don't go down the wrong path of making the unit test assertions fit the results. Your class is then robust and meets requirements when all your unit tests pass.
If you're trying to test existing code that you're reluctant or unable to change, reflection is a good choice.
If the class's design is still flexible, and you've got a complicated private method that you'd like to test separately, I suggest you pull it out into a separate class and test that class separately. This doesn't have to change the public interface of the original class; it can internally create an instance of the helper class and call the helper method.
If you want to test difficult error conditions coming from the helper method, you can go a step further. Extract an interface from the helper class, add a public getter and setter to the original class to inject the helper class (used through its interface), and then inject a mock version of the helper class into the original class to test how the original class responds to exceptions from the helper. This approach is also helpful if you want to test the original class without also testing the helper class.
Testing private methods breaks the encapsulation of your class because every time you change the internal implementation you break client code (in this case, the tests).
So don't test private methods.
The answer from JUnit.org FAQ page:
But if you must...
If you are using JDK 1.3 or higher, you can use reflection to subvert
the access control mechanism with the aid of the PrivilegedAccessor.
For details on how to use it, read this article.
If you are using JDK 1.6 or higher and you annotate your tests with
#Test, you can use Dp4j to inject reflection in your test methods. For
details on how to use it, see this test script.
P.S. I'm the main contributor to Dp4j. Ask me if you need help. :)
If you want to test private methods of a legacy application where you can't change the code, one option for Java is jMockit, which will allow you to create mocks to an object even when they're private to the class.
PowerMockito is made for this.
Use a Maven dependency:
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-core</artifactId>
<version>2.0.7</version>
<scope>test</scope>
</dependency>
Then you can do
import org.powermock.reflect.Whitebox;
...
MyClass sut = new MyClass();
SomeType rval = Whitebox.invokeMethod(sut, "myPrivateMethod", params, moreParams);
I tend not to test private methods. There lies madness. Personally, I believe you should only test your publicly exposed interfaces (and that includes protected and internal methods).
If you're using JUnit, have a look at junit-addons. It has the ability to ignore the Java security model and access private methods and attributes.
Here is my generic function to test private fields:
protected <F> F getPrivateField(String fieldName, Object obj)
throws NoSuchFieldException, IllegalAccessException {
Field field =
obj.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
return (F)field.get(obj);
}
Please see below for an example;
The following import statement should be added:
import org.powermock.reflect.Whitebox;
Now you can directly pass the object which has the private method, method name to be called, and additional parameters as below.
Whitebox.invokeMethod(obj, "privateMethod", "param1");
I would suggest you refactoring your code a little bit. When you have to start thinking about using reflection or other kind of stuff, for just testing your code, something is going wrong with your code.
You mentioned different types of problems. Let's start with private fields. In case of private fields I would have added a new constructor and injected fields into that. Instead of this:
public class ClassToTest {
private final String first = "first";
private final List<String> second = new ArrayList<>();
...
}
I'd have used this:
public class ClassToTest {
private final String first;
private final List<String> second;
public ClassToTest() {
this("first", new ArrayList<>());
}
public ClassToTest(final String first, final List<String> second) {
this.first = first;
this.second = second;
}
...
}
This won't be a problem even with some legacy code. Old code will be using an empty constructor, and if you ask me, refactored code will look cleaner, and you'll be able to inject necessary values in test without reflection.
Now about private methods. In my personal experience when you have to stub a private method for testing, then that method has nothing to do in that class. A common pattern, in that case, would be to wrap it within an interface, like Callable and then you pass in that interface also in the constructor (with that multiple constructor trick):
public ClassToTest() {
this(...);
}
public ClassToTest(final Callable<T> privateMethodLogic) {
this.privateMethodLogic = privateMethodLogic;
}
Mostly all that I wrote looks like it's a dependency injection pattern. In my personal experience it's really useful while testing, and I think that this kind of code is cleaner and will be easier to maintain. I'd say the same about nested classes. If a nested class contains heavy logic it would be better if you'd moved it as a package private class and have injected it into a class needing it.
There are also several other design patterns which I have used while refactoring and maintaining legacy code, but it all depends on cases of your code to test. Using reflection mostly is not a problem, but when you have an enterprise application which is heavily tested and tests are run before every deployment everything gets really slow (it's just annoying and I don't like that kind of stuff).
There is also setter injection, but I wouldn't recommended using it. I'd better stick with a constructor and initialize everything when it's really necessary, leaving the possibility for injecting necessary dependencies.
A private method is only to be accessed within the same class. So there is no way to test a “private” method of a target class from any test class. A way out is that you can perform unit testing manually or can change your method from “private” to “protected”.
And then a protected method can only be accessed within the same package where the class is defined. So, testing a protected method of a target class means we need to define your test class in the same package as the target class.
If all the above does not suits your requirement, use the reflection way to access the private method.
As many above have suggested, a good way is to test them via your public interfaces.
If you do this, it's a good idea to use a code coverage tool (like EMMA) to see if your private methods are in fact being executed from your tests.
Today, I pushed a Java library to help testing private methods and fields. It has been designed with Android in mind, but it can really be used for any Java project.
If you got some code with private methods or fields or constructors, you can use BoundBox. It does exactly what you are looking for.
Here below is an example of a test that accesses two private fields of an Android activity to test it:
#UiThreadTest
public void testCompute() {
// Given
boundBoxOfMainActivity = new BoundBoxOfMainActivity(getActivity());
// When
boundBoxOfMainActivity.boundBox_getButtonMain().performClick();
// Then
assertEquals("42", boundBoxOfMainActivity.boundBox_getTextViewMain().getText());
}
BoundBox makes it easy to test private/protected fields, methods and constructors. You can even access stuff that is hidden by inheritance. Indeed, BoundBox breaks encapsulation. It will give you access to all that through reflection, but everything is checked at compile time.
It is ideal for testing some legacy code. Use it carefully. ;)
First, I'll throw this question out: Why do your private members need isolated testing? Are they that complex, providing such complicated behaviors as to require testing apart from the public surface? It's unit testing, not 'line-of-code' testing. Don't sweat the small stuff.
If they are that big, big enough that these private members are each a 'unit' large in complexity—consider refactoring such private members out of this class.
If refactoring is inappropriate or infeasible, can you use the strategy pattern to replace access to these private member functions / member classes when under unit test? Under unit test, the strategy would provide added validation, but in release builds it would be simple passthrough.
I want to share a rule I have about testing which particularly is related to this topic:
I think that you should never adapt production code in order to
indulge easer writing of tests.
There are a few suggestions in other posts saying you should adapt the original class in order to test a private method - please red this warning first.
If we change the accessibility of a method/field to package private or protected, just in order to have it accessible to tests, then we defeat the purpose of existence of private access directive.
Why should we have private fields/methods/classes at all when we want to have test-driven development? Should we declare everything as package private, or even public then, so we can test without any effort?—I don't think so.
From another point of view: Tests should not burden performance and execution of the production application.
If we change production code just for the sake of easier testing, that may burden performance and the execution of the application in some way.
If someone starts to change private access to package private, then a developer may eventually come up to other "ingenious ideas" about adding even more code to the original class. This would make additional noise to readability and can burden the performance of the application.
With changing of a private access to some less restrictive, we are opening the possibility to a developer for misusing the new situation in the future development of the application. Instead of enforcing him/her to develop in the proper way, we are tempting him/her with new possibilities and giving him ability to make wrong choices in the future.
Of course there might be a few exceptions to this rule, but with clear understanding, what is the rule and what is the exception? We need to be absolutely sure we know why that kind of exception is introduced.

How should I order the members of a C++ class?

Is it better to have all the private members, then all the protected ones, then all the public ones? Or the reverse? Or should there be multiple private, protected and public labels so that the operations can be kept separate from the constructors and so on? What issues should I take into account when making this decision?
I put the public interface first, but I didn't always do this. I used to do things backwards to this, with private, then protected, then public. Looking back, it didn't make a lot of sense.
As a developer of a class, you'll likely be well acquainted with its "innards" but users of the class don't much care, or at least they shouldn't. They're mostly interested in what the class can do for them, right?
So I put the public first, and organize it typically by function/utility. I don't want them to have to wade through my interface to find all the methods related to X, I want them to see all that stuff together in an organized manner.
I never use multiple public/protected/private sections - too confusing to follow in my opinion.
Google favors this order: "Typedefs and Enums, Constants, Constructors, Destructor, Methods, including static methods, Data Members, including static data members."
Matthew Wilson (Safari subscription required) recommends the following order: "Construction, Operations, Attributes, Iteration, State, Implementation, Members, and my favorite, Not to be implemented."
They offer good reasons, and this kind of approach seems to be fairly standard, but whatever you do, be consistent about it.
Coding style is a source for surprisingly heated conversation, with that in mind I risk providing a different opinion:
Code should be written so it is most readable for humans. I complete agree with this statement that was given here several times.
The deviation is which roll are we taking about.
To help the user of the class understand how to use it, one should write and maintain proper documentation. A user should never be needing to read the source code to be able to use the class. If this is done (either manually or using in-source documentation tools) then the order in which public and private class members are defined in the source does not matter for the user.
However, for someone who needs to understand the code, during code review, pull request, or maintenance, the order matters a great deal - the rule is simple:
items should be defined before they are used
This is neither a compiler rule not is it a strictly public v.s. private rule, but common sense - human readability rule. We read code sequentially, and if we need "juggle" back and forth every time we see a class member used, but don't know its type for example, it adversely affects the readability of the code.
Making a division strictly on private v.s. public violates this rule because private class members will appear after they have been used in any public method.
It's my opinion, and I would wager a guess that most people would agree, that public methods should go first. One of the core principles of OO is that you shouldn't have to care about implementation. Just looking at the public methods should tell you everything you need to know to use the class.
As always, write your code for humans first. Consider the person who will be using your class and place the most important members/enums/typedefs/whatever to them at the top.
Usually this means that public members are at the top since that's what most consumers of your class are most interested in. Protected comes next followed by privates. Usually.
There are some exceptions.
Occasionally initialisation order is important and sometimes a private will need to be declared before a public. Sometimes it's more important for a class to be inherited and extended in which case the protected members may be placed higher up. And when hacking unit tests onto legacy code sometimes it's just easier to expose public methods - if I have to commit this near-sin I'll place these at the bottom of the class definition.
But they're relatively rare situations.
I find that most of the time "public, protected, private" is the most useful to consumers of your class. It's a decent basic rule to stick by.
But it's less about ordering by access and more about ordering by interest to the consumer.
I usually define first the interface (to be read), that is public, then protected, then private stuff. Now, in many cases I go a step forward and (if I can handle it) use the PIMPL pattern, fully hiding all the private stuff from the interface of the real class.
class Example1 {
public:
void publicOperation();
private:
void privateOperation1_();
void privateOperation2_();
Type1 data1_;
Type2 data2_;
};
// example 2 header:
class Example2 {
class Impl;
public:
void publicOperation();
private:
std::auto_ptr<Example2Impl> impl_;
};
// example2 cpp:
class Example2::Impl
{
public:
void privateOperation1();
void privateOperation2();
private: // or public if Example2 needs access, or private + friendship:
Type1 data1_;
Type2 data2_;
};
You can notice that I postfix private (and also protected) members with an underscore. The PIMPL version has an internal class for which the outside world does not even see the operations. This keeps the class interface completely clean: only real interface is exposed. No need to argue about order.
There is an associated cost during the class construction as a dynamically allocated object must be built. Also this works really well for classes that are not meant to be extended, but has some short comings with hierarchies. Protected methods must be part of the external class, so you cannot really push them into the internal class.
I tend to follow the POCO C++ Coding Style Guide.
i think it's all about readability.
Some people like to group them in a fixed order, so that whenever you open a class declaration, you quickly know where to look for e.g. the public data members.
In general, I feel that the most important things should come first. For 99.6% of all classes, roughly, that means the public methods, and especially the constructor. Then comes public data members, if any (remember: encapsulation is a good idea), followed by any protected and/or private methods and data members.
This is stuff that might be covered by the coding standards of large projects, it can be a good idea to check.
In our project, we don't order the members according to access, but by usage. And by that I mean, we order the members as they are used. If a public member uses a private member in the same class, that private member is usually located in front of the public member somewhere, as in the following (simplistic) example:
class Foo
{
private:
int bar;
public:
int GetBar() const
{
return bar;
}
};
Here, the member bar is placed before the member GetBar() because the former is used by the latter. This can result in multiple access sections, as in the following example:
class Foo
{
public:
typedef int bar_type;
private:
bar_type bar;
public:
bar_type GetBar() const
{
return bar;
}
};
The bar_type member is used by the bar member, see?
Why is this? I dunno, it seemed more natural that if you encounter a member somewhere in the implementation and you need more details about that (and IntelliSense is screwed up again) that you can find it somewhere above from where you're working.
In practice, it rarely matters. It's primarily a matter of personal preference.
It's very popular to put public methods first, ostensibly so that users of the class will be able to find them more easily. But headers should never be your primary source of documentation, so basing "best practices" around the idea that users will be looking at your headers seems to miss the mark for me.
It's more likely for people to be in your headers if they're modifying the class, in which case they should care about the private interface.
Whichever you choose, make your headers clean and easy to read. Being able to easily find whatever info I happen to be looking for, whether I'm a user of the class or a maintainer of the class, is the most important thing.
It is really helpful to the folks that will use your class to list the public interface first. It's the part they care about and can use. Protected and private can follow along after.
Within the public interface, it's convenient to group constructors, property accessors and mutators, and operators in distinct groups.
Note that (depending on your compiler and dynamic linker), you can retain compatibility with previous versions of a shared library by only adding to the end of the class (i.e. to the end of the interface), and not removing or changing anything else. (This is true for G++ and libtool, and the three part versioning scheme for GNU/Linux shared libraries reflects this.)
There's also the idea that you should order members of the class to avoid wasted space due to memory alignment; one strategy is to order members from smallest to largest size. I've never done this either in C++ or C though.
Overall, your public interface should come before anything, because that's the main/only thing that users of your classes should be interested in. (Of course, in reality that doesn't always hold, but it's a good start.)
Within that, member types and constants are best first, followed by construction operators, operations, and then member variables.
Put the private fields first.
With modern IDEs, people don't read the class to figure out what it's public interface is.
They just use intellisence (or a class browser) for that.
If someone is reading through the class definition, it's usually because they want to understand how it works.
In that case, knowing the fields helps the most. It tells you what the parts of the object are.
binary compatibility
There are a few concrete reasons for the ordering of class members.
These have to do with binary compatibility.
Binary compatibility mainly affects changes to system DLLs and device drivers.
If you're not interested in these, ignore this answer.
Public members must go before private members.
This is so you can mix and change private members without affecting the location of public data.
New public members must go last.
This again avoids affecting the position of existing public members.
The same ordering applies to vtable members.
Apart from this there's no reason to not to follow your own/your colleagues' preferences.
Depends entirely on your preference. There is no "the right way".
When doing C++ in my own pet projects I personally keep convention that I put access modifier before each member or method declaration.