Unit testing different class hierarchies - oop

What would be the best approach to make unit tests that consider different class hierarchies, like:
I have a base class Car and another base class Animal.
Car have the derived classes VolksWagen and Ford.
Animal have the derived classes Dog and Cat.
How would you develop test that decide at run-time what kind of object are you going to use.
What is the best approach to implement these kind of tests without using code replication, considering that these tests will be applied for milions of objects
from different hierarchies ?
This was an interview question asked to a friend of mine.

Problem as I see it: Avoid repeating common tests to validate n derivations of a common base type.
Create an abstract test fixture. Here you write the tests against the base type & in a abstract base class (search term 'abstract test fixture') with a abstract method GetTestSubject(). Derivations of this type override the method to return an instance of the type to be tested. So you'd need to write N subtypes with a single overridden method but your tests would be written once.
Some unit testing frameworks like NUnit support 'parameterized tests' (search term) - where you have to implement a method/property which would return all the objects that the tests need to be run against. It would then run one/all tests against each such object at run time. This way you don't need to write N derivations - just one method.

Here is one approach that I've used before (well, a variant of this).
Let's assume that you have some sort of common method (go) on Car that you want to test for all classes, and some specific method (breakDown) that has different behavior in the subclass, thus:
public class Car {
protected String engineNoise = null;
public void go() {
engineNoise = "vroom";
}
public void breakDown() {
engineNoise = null;
}
public String getEngineNoise() {
return engineNoise;
}
}
public class Volkswagen extends Car {
public void breakDown() {
throw new UnsupportedOperationException();
}
}
Then you could define a test as follows:
public abstract class CarTest<T extends Car> {
T car;
#Before
public void setUp() {
car = createCar();
}
#Test
public void testVroom() {
car.go();
assertThat( car.getEngineNoise(), is( "vroom" ) );
}
#Test
public void testBreakDown() {
car.breakDown();
assertThat( car.getEngineNoise(), is( null ) );
}
protected abstract T createCar();
}
Now, since Volkswagen needs to do something different in the testBreakDown method -- and may possibly have other methods that need testing -- then you could use the following VolkswagenTest.
public class VolkswagenTest extends CarTest<Volkswagen> {
#Test(expected = UnsupportedOperationException.class)
public void testBreakdown() {
car.breakDown();
}
protected Volkswagen createCar() {
return new Volkswagen();
}
}
Hope that helps!

Actually Unit Test refers to Method Test, when you want to write a unit test you must think to the functionality of a method that you want to write and test, and then create class(es) and method(s) for testing that. by considering this approach when you design and write your code, maybe create hierarchies of classes or just single class or any type of other designs.
but when you have to use existing design like something you mentioned above, then the best practice is to use Interfaces or Base Classes for dependecy objects, because in this way you can mock or stub those classes easily.

Related

How to simply introduce a new method on a large subset of classes implementing an interface?

I have an interface, say IVehicle, which is implemented in 100s of classes, some of them are variety of 4 wheeler and some are two wheeler dervied types.
I need to introduce a new method for all the 4 wheeler classes, lets say there are 50 of them. My challenge is to reduce the effort as much as I can.
I suggested, to introduce a new interface / abstract class with a method definition. But this require to change every 4 wheeler class declaration and extend with an extra parent.
Is there any possible way?
If you really want to avoid changing all those classes and want a solution that can be considered to be OO, one thing you can do is decorate those classes where they are used and need this extra behaviour.
I'll use C# for example code as you mentioned you're looking for C#/Java solution.
interface IVehicle
{
void DoThisNormalThing();
// ...
}
interface IBetterVehicle : IVehicle
{
void DoThisNeatThing();
}
class FourWheelVehicle : IVehicle
{
public void DoThisNormalThing()
{
// ...
}
// ...
}
class BetterFourWheelVehicle : IBetterVehicle
{
private readonly _vehicle;
public BetterFourWheelVehicle(IVehicle vehicle)
{
_vehicle = vehicle;
}
public void DoThisNormalThing()
{
_vehicle.DoThisNormalThing();
}
public void DoThisNeatThing()
{
// ...
}
// ...
}
Then usage:
var vehicle = new FourWheelVehicle();
var betterVehicle = new BetterFourWheelVehicle(vehicle);
betterVehicle.DoThisNeatThing();
This can be done using extension methods as well (and would result in a little less code and fewer allocated objects), but as this question is tagged with [oop] I wouldn't say extension methods are an OO construct. They're much more aligned with procedural style as they turn your objects into bags of procedures.

Avoid adding/extending methods to interface

I have a scenario , where my current interface looks like
public interface IMathematicalOperation
{
void AddInt();
}
After an year i expect the interface to be extended with AddFloat method and also expect 100 users already consuming this interface. When i extend the interface with a new method after an year i don't want these 100 classes to get changed.
So how can i tackle this situation ? Is there any design pattern available already to take care of this situation ?
Note: i understand that i can have a abstract class which implement this interface and make all the methods virtual , so that clients can inherit from this class rather than the interface and override the methods . When i add a new method only the abstract class will be changed and the clients who are interested in the method will override the behavior (minimize the change) .
Is there any other way of achieving the same result (like having a method named Add and based on certain condition it will do Float addition or Integer addition) ?
Edit 1:
The new method gets added to the interface also needs to be called automatically along with the existing methods(like chain of responsibility pattern).
There are at least two possible solution I can think of:
Derive your new interface from your old interface
public interface IMathematicalOperation
{
void AddInt();
}
public interface IFloatingPointMathematicalOperation : IMathematicalOperation
{
void AddFloat();
}
Have simply a parallel interface which contains the new method and have all classes which need the new interface derive from it
I'd suggest the second solution, since I don't understand why you would want an established interface to change.
I encountered a similar issue some time ago and found the best way was not to try and extend an existing interface, but to provide different versions of the interface with each new interface providing extra functionality. Over time I found that was not adding functionality on a regular basis, may once a year, so adding extra interfaces was never really an issue.
So, for example this is your first version of the interface:
public interface IMathematicalOperation
{
void AddInt();
}
This interface would then be implemented on a class like this:
public class MathematicalOperationImpl : IMathematicalOperation
{
public void AddInt()
{
}
}
Then when you need to add new functionality, i.e. create a version 2, you would create another interface with the same name, but with a "2" on the end:
public interface IMathematicalOperation2 : IMathematicalOperation
{
void AddFloat();
}
And the MathematicalOperationImpl would be extended to implement this new interface:
public class MathematicalOperationImpl : IMathematicalOperation, IMathematicalOperation2
{
public void AddInt()
{
}
public void AddFloat()
{
}
}
All of your new/future clients could start using the version 2 interface, but your existing clients would continue to work because they will only know about the first version of the interface.
The options provided are syntactically viable but then, as is obvious, they won't apply to any previous users.
A better option would be to use the Visitor pattern
The pattern is best understood when you think about the details of OO code
this.foo(); // is identical to
foo(this);
Remember that there is always a hidden 'this' parameter passed with every instance call.
What the visitor pattern attempts to do is generalize this behavior using Double dispatch
Let's take this a hair further
public interface MathematicalOperation
{
void addInt();
void accept(MathVisitor v);
}
public interface MathVisitor {
void visit(MathematicalOperation operation);
}
public class SquareVistor implements MathVisitor {
void visit(MathematicalOperation operation) {
operation.setValue(operation.getValue() * 2);
}
}
public abstract class AbstractMathematicalOperation implements MathematicalOperation {
public void accept(MathVisitor f) {
f.visit(this); // we are going to do 'f' on 'this'. Or think this.f();
}
}
public class MyMathOperation extends AbstractMathematicalOperation {
}
someMathOperation.visit(new SquareVisitor()); // is now functionally equivalent to
someMathOperation.square();
The best bet would be for you to roll-out your initial interface with a visitor requirements, then immediately roll-out an abstract subclass that gives this default implementation so it's cooked right in (As the above class is). Then everyone can just extend it. I think you will find this gives you the flexibility you need and leaves you will the ability to work with legacy classes.

Singleton subclass

I have an abstract base class and an implementation class like:
public abstract class Base
{
public Base getInstance( Class<? extends Base> clazz )
{
//expected to return a singleton instance of clazz's class
}
public abstract absMeth();
}
public A extends Base
{
//expected to be a singleton
}
In this example I can make A to be a singleton and even write getInstance in Base to return a singleton object of A for every call, doing this way:
public abstract class Base
{
public Base getInstance( Class<? extends Base> clazz )
{
try
{
return clazz.getDeclaredMethod("getInstance").invoke(null,null);
}
}
public abstract void absMeth();
}
public A extends Base
{
private static A inst;
private A(){}
public static A getInstance( )
{
if( inst!= null)
inst = new A();
return inst;
}
public void absMeth(){
//...
}
}
But my concern is how do I ensure that if somebody writes another class class B extends Base it should also be a singleton and it necessarily implements a static method called getInstance?
In other words I need to enforce this as a specification for all classes extending with the Base class.
You cannot trust classes that extend you to create a single instance of themselves1: even if you could somehow ensure that they all implement getInstance, there is no way to tell that inside that method they check inst before constructing a new instance of themselves.
Stay in control of the process: create a Map<Class,Base>, and instantiate the class passed in through reflection2. Now your code can decide whether to create an instance or not, without relying on the getInstance of a subclass.
1 A popular saying goes, "If you want a job done right, do it yourself."
2 Here is a link describing a solution based on setAccessible(true)
Singleton is a design pattern, not a language feature. It is pretty much impossible to somehow enforce it on the inheritance tree through syntax.
It certainly is possible to require all subclasses to implement a method by declaring it abstract but there is no way to control implementation details. Singleton is all about implementation details.
But why is this a concern at all? Do not make your app dependant on internal details of someone else's code. It is Bad Design™ and having this issue is a sure sign of it. Code against a well-defined interface and avoid relying on internal details.

When is an "interface" useful?

OOP interfaces.
In my own experience I find interfaces very useful when it comes to design and implement multiple inter-operating modules with multiple developers. For example, if there are two developers, one working on backend and other on frontend (UI) then they can start working in parallel once they have interfaces finalized. Thus, if everyone follows the defined contract then the integration later becomes painless. And thats what interfaces precisely do - define the contract!
Basically it avoids this situation :
Interfaces are very useful when you need a class to operate on generic methods implemented by subclasses.
public class Person
{
public void Eat(IFruit fruit)
{
Console.WriteLine("The {0} is delicious!",fruit.Name);
}
}
public interface IFruit
{
string Name { get; }
}
public class Apple : IFruit
{
public string Name
{
get { return "Apple"; }
}
}
public class Strawberry : IFruit
{
public string Name
{
get { return "Strawberry"; }
}
}
Interfaces are very useful, in case of multiple inheritance.
An Interface totally abstracts away the implementation knowledge from the client.
It allows us to change their behavior dynamically. This means how it will act depends on dynamic specialization (or substitution).
It prevents the client from being broken if the developer made some changes
to implementation or added new specialization/implementation.
It gives an open way to extend an implementation.
Programming language (C#, java )
These languages do not support multiple inheritance from classes, however, they do support multiple inheritance from interfaces; this is yet another advantage of an interface.
Basically Interfaces allow a Program to change the Implementation without having to tell all clients that they now need a "Bar" Object instead of a "Foo" Object. It tells the users of this class what it does, not what it is.
Example:
A Method you wrote wants to loop through the values given to it. Now there are several things you can iterate over, like Lists, Arrays and Collections.
Without Interfaces you would have to write:
public class Foo<T>
{
public void DoSomething(T items[])
{
}
public void DoSomething(List<T> items)
{
}
public void DoSomething(SomeCollectionType<T> items)
{
}
}
And for every new iteratable type you'd have to add another method or the user of your class would have to cast his data. For example with this solution if he has a Collection of FooCollectionType he has to cast it to an Array, List or SomeOtherCollectionType.
With interfaces you only need:
public class Foo<T>
{
public void DoSomething(IEnumerable<T> items)
{
}
}
This means your class only has to know that, whatever the user passes to it can be iterated over. If the user changes his SomeCollectionType to AnotherCollectionType he neither has to cast nor change your class.
Take note that abstract base classes allow for the same sort of abstraction but have some slight differences in usage.

Where to put methods used by multiple classes?

To show an example what is this question about:
I have currently a dilemma in PHP project I'm working on. I have in mind a method that will be used by multiple classes (UIs in this case - MVC model), but I'm not sure how to represent such methods in OO design. The first thing that came into my mind was to create a class with static functions that I'd call whenever I need them. However I'm not sure if it's the right thing to do.
To be more precise, I want to work, for example, with time. So I'll need several methods that handle time. I was thinking about creating a Time class where I'd be functions that check whether the time is in correct format etc.
Some might say that I shouldn't use class for this at all, since in PHP I can still use procedural code. But I'm more interested in answer that would enlighten me how to approach such situations in OOP / OOD.
So the actual questions are: How to represent such methods? Is static function approach good enough or should I reconsider anything else?
I would recommend creating a normal class the contains this behavior, and then let that class implement an interface extracted from the class' members.
Whenever you need to call those methods, you inject the interface (not the concrete class) into the consumer. This lets you vary the two independently of each other.
This may sound like more work, but is simply the Strategy design pattern applied.
This will also make it much easier to unit test the code, because the code is more loosely coupled.
Here's an example in C#.
Interface:
public interface ITimeMachine
{
IStopwatch CreateStopwatch();
DateTimeOffset GetNow();
}
Production implementation:
public class RealTimeMachine : ITimeMachine
{
#region ITimeMachine Members
public IStopwatch CreateStopwatch()
{
return new StopwatchAdapter();
}
public DateTimeOffset GetNow()
{
return DateTimeOffset.Now;
}
#endregion
}
and here's a consumer of the interface:
public abstract class PerformanceRecordingSession : IDisposable
{
private readonly IStopwatch watch;
protected PerformanceRecordingSession(ITimeMachine timeMachine)
{
if (timeMachine == null)
{
throw new ArgumentNullException("timeMachine");
}
this.watch = timeMachine.CreateStopwatch();
this.watch.Start();
}
public abstract void Record(long elapsedTicks);
public virtual void StopRecording()
{
this.watch.Stop();
this.Record(this.watch.ElapsedTicks);
}
}
Although you say you want a structure for arbitrary, unrelated functions, you have given an example of a Time class, which has many related functions. So from an OO point of view you would create a Time class and have a static function getCurrentTime(), for example, which returns an instance of this class. Or you could define that the constuctors default behaviour is to return the current time, whichever you like more. Or both.
class DateTime {
public static function getNow() {
return new self();
}
public function __construct() {
$this->setDateTime('now');
}
public function setDateTime($value) {
#...
}
}
But apart from that, there is already a builtin DateTime class in PHP.
Use a class as a namespace. So yes, have a static class.
class Time {
public static function getCurrentTime() {
return time() + 42;
}
}
I don't do PHP, but from an OO point of view, placing these sorts of utility methods as static methods is fine. If they are completely reusable in nature, consider placing them in a utils class.