How to assert if a method was called within another method in RhinoMocks? - rhino-mocks

I have a class that has two methods. One method needs to call the other method and in my test I want to assert that it was called.
public class Tasks : ITasks
{
public void MethodOne()
{
MethodTwo(1);
}
public int MethodTwo(int i)
{
return i + 1;
}
}
I want to mock Tasks and do something like tasks.AssertWasCalled(x => x.MethodTwo(1)). Must MethodTwo be virtual?

The concept you're looking for is partial mocks (this shows old syntax, but I don't remember the new one off the top of my head). You should read up on it. Essentially you create the mock on Tasks (not ITasks) and tell it to mock out only MethodTwo (which needs to be virtual).
However...you might want to reconsider your design. What is ITasks? What is the role? Are they different actual tasks? Is there any reason why you would want them in the same class? My understanding is that partial mocks is only included for when you need to test legacy components - I've never found a use for it.

Of course my thinking at that time was flawed. I should be mocking ITasks, not the implementation (Tasks):
ITasks tasks = MockRepository.GenerateMock<ITasks>();
tasks.AssertWasCalled(x => x.MethodTwo(Arg<int>.Is.Equal(1)));

Related

Does this simple modeling example violate SOLID principles and how to unit test it

I am trying to implement a simple validator class system which respect SOLID principles and for unit testing purpose.
Suppose I have some simple validators (mandatory, integer, greaterThan ...) and now I want to implement a more complex validator which call several simple validators (example Form Validator which use some validators)
This is very inspired from Zend and other framework.
The question is, how SOLID principle are applied or violated here and how unit testing should be done for this model?
I think I could Unit Test each simple validator easily but not the complex FormValidator
interface ICheckable
{
public function check($data);
}
class MandatoryValidator implements ICheckable
{
private $_property;
public function __construct($property)
{
$this->_property = $property;
}
public function check($data)
{
return isset($data[$property]);
}
}
class IntegerValidator implements ICheckable
{
...
}
class FormValidator implements ICheckable
{
public function check($data)
{
$mandatoryValidator = new MandatoryValidator(array('LOGIN'));
if ($mandatoryValidator->check($data) == false)
{
return false;
}
$integerValidator = new IntegerValidator();
if ($integerValidator->check($data['AMOUNT']) == false)
{
return false;
}
...
return true;
}
}
First - good job with the ICheckable Interface. That's a good start.
Lets tackle the S. Single Responsibility Principle:
That's the principle that states, "a class should only have one reason to change"
Is the S. Respected in all the classes?
(Simple Responsibility.)
The two current validators respect this.
Is FormValidator has only one responsibility? I can see it does 3 things:
Creates the Validators.
Calls the 2 validators.
Checks the validator resutls.
The problem with this design is that everytime you have a new Validator, you have to create it, call it, and check its return value. This violates the O in the SOLID Principles. (Open / Close)
The form Validator should receive a "custom" List of ICheckable. This "custom" list should also impelment ICheckable so you can just call it. This "custom" List will iterate through its list of ICheckable. That will be it's only responsibility.
Then, The Result has to be evaluated. When a function returns a value, you have to process it. In general this means more code, an extra IF statement. Those two should give you a hint: too much responsibility.
So in order to make this SOLID, you should pass your validators a Callback Interface that will serve to process the validator output. Your sample is quite simple, a validator returns true of false. Which can be represented by two "output" methods - Validated() or ValidationFailed(). O_o, this looks like a very nice "output" interface for your validators and could be implemented by the FormValidator. This design would comply the S. O. L. I. D. of the principles.
Remember, when you first create the FormValidator, you have to create the two Validators, the Custom List and connect everything together.
Then you would be able to unit test all very simple classes, very quickly. (try to start writing your test first)
Note: In general if you tackle the S. Properly, the other principles are very easy to implement.
Hope this helps. Let me know if you need more information.

Design Pattern for late binding class (without switch case for class assignment)

I have a base class where all common functions are written. I many classes which override this functions by virtual keyword. Like,
public class Base
{
public virtual void sample()
{
..............
}
}
public class a : Base
{
public override sample()
{
}
}
public class implement
{
public void ToSample()
{
Base baseclass = new Base();
Switch(test)
{
case a: baseclass = a();
break;
case b: baseclass = b();
break;
}
baseclass.sample();
}
}
This perfect code for current situation but now I have more class to be assign in switch case. It is not good practice for adding huge amount of cases so I want something that automatically assign child class.
Is anybody know something to be implement ?
As stated in the comment, you can decouple the implementation by using dependency injection. Note however, that in some cases you have no choice but doing that kind of switch (e.g. when you need to create a class based on a text received in a socket). In such cases the important thing is to always keep the switch statement encapsulated in one method and make your objects rely on it (or, in other words, don't copy-and-paste it everywhere :)). The idea here is too keep your system isolated from a potentially harmful code. Of course that if you add a new class you will have to go and modify that method, however you will only have to do it in one time and in one specific place.
Another approach that I have seen (and sometimes used) is to build a mapping between values an classes. So, if your class-creation switch depends on an integer code, you basically create a mapping between codes and classes. What you are doing here is turning a "static" switch into a dynamic behavior, since you can change the mappings contents at any time and thus alter the way your program behaves. A typical implementation would be something like (sorry for the pseudocode, I'm not familiar with C#):
public class implement
{
public void ToSample()
{
class = this.mapping.valueForKey(test);
Base baseclass = new class();
baseclass.sample();
}
}
Note however that for this example to work you need reflection support, which varies according to the language you are using (again, sorry but I don't know the C# specifics).
Finally, you can also check the creational family of patterns for inspiration regarding object creation issues and some well known forms of solving them.
HTH

Monkey Patching in C#

Is it possible to extend or modify the code of a C# class at runtime?
My question specifically revolves around Monkey Patching / Duck Punching or Meta Object Programming (MOP), as it happens in scripting languages such as Groovy, Ruby etc.
For those still stumbling on this question in the present day, there is indeed a present-day library called Harmony that relatively-straightforwardly enables such monkey-patching at runtime. Its focus is on video game modding (particularly games built with Unity), but there ain't much stopping folks from using it outside of that use case.
Copying the example from their introduction, if you have an existing class like so:
public class SomeGameClass
{
public bool isRunning;
public int counter;
private int DoSomething()
{
if (isRunning)
{
counter++;
}
return counter * 10;
}
}
Then Harmony can patch it like so:
using HarmonyLib;
using Intro_SomeGame;
public class MyPatcher
{
// make sure DoPatching() is called at start either by
// the mod loader or by your injector
public static void DoPatching()
{
var harmony = new Harmony("com.example.patch");
harmony.PatchAll();
}
}
[HarmonyPatch(typeof(SomeGameClass))]
[HarmonyPatch("DoSomething")]
class Patch01
{
static AccessTools.FieldRef<SomeGameClass, bool> isRunningRef =
AccessTools.FieldRefAccess<SomeGameClass, bool>("isRunning");
static bool Prefix(SomeGameClass __instance, ref int ___counter)
{
isRunningRef(__instance) = true;
if (___counter > 100)
return false;
___counter = 0;
return true;
}
static void Postfix(ref int __result)
{
__result *= 2;
}
}
Here, we have a "prefix" patch which gets inserted before the original method runs, allowing us to set variables within the method, set fields on the method's class, or even skip the original method entirely. We also have a "postfix" patch which gets inserted after the original method runs, and can manipulate things like the return value.
Obviously this ain't quite as nice as the sorts of monkey-patching you can do in e.g. Ruby, and there are a lot of caveats that might hinder its usefulness depending on your use case, but in those situations where you really do need to alter methods, Harmony's a pretty proven approach to doing so.
Is it possible to extend or modify the code of a C# class at run-time?
No it is not possible to do this in .NET. You could write derived classes and override methods (if they are virtual) but you cannot modify an existing class. Just imagine if what you were asking was possible: you could modify the behavior of some existing system classes like System.String.
You may also take a look at Extension methods to add functionality to an existing class.
You can add functionality, but you cannot change or remove functionality.
You can extend classes by adding extra methods, but you cannot override them because added methods have always lower priority than existing ones.
For more info, check Extension Methods in C# Programming Guide.

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.

Can a class return an object of itself

Can a class return an object of itself.
In my example I have a class called "Change" which represents a change to the system, and I am wondering if it is in anyway against design principles to return an object of type Change or an ArrayList which is populated with all the recent Change objects.
Yes, a class can have a method that returns an instance of itself. This is quite a common scenario.
In C#, an example might be:
public class Change
{
public int ChangeID { get; set; }
private Change(int changeId)
{
ChangeID = changeId;
LoadFromDatabase();
}
private void LoadFromDatabase()
{
// TODO Perform Database load here.
}
public static Change GetChange(int changeId)
{
return new Change(changeId);
}
}
Yes it can. In fact, that's exactly what a singleton class does. The first time you call its class-level getInstance() method, it constructs an instance of itself and returns that. Then subsequent calls to getInstance() return the already-constructed instance.
Your particular case could use a similar method but you need some way of deciding the list of recent changes. As such it will need to maintain its own list of such changes. You could do this with a static array or list of the changes. Just be certain that the underlying information in the list doesn't disappear - this could happen in C++ (for example) if you maintained pointers to the objects and those objects were freed by your clients.
Less of an issue in an automatic garbage collection environment like Java since the object wouldn't disappear whilst there was still a reference to it.
However, you don't have to use this method. My preference with what you describe would be to have two clases, changelist and change. When you create an instance of the change class, pass a changelist object (null if you don't want it associated with a changelist) with the constructor and add the change to that list before returning it.
Alternatively, have a changelist method which creates a change itself and returns it, remembering the change for its own purposes.
Then you can query the changelist to get recent changes (however you define recent). That would be more flexible since it allows multiple lists.
You could even go overboard and allow a change to be associated with multiple changelists if so desired.
Another reason to return this is so that you can do function chaining:
class foo
{
private int x;
public foo()
{
this.x = 0;
}
public foo Add(int a)
{
this.x += a;
return this;
}
public foo Subtract(int a)
{
this.x -= a;
return this;
}
public int Value
{
get { return this.x; }
}
public static void Main()
{
foo f = new foo();
f.Add(10).Add(20).Subtract(1);
System.Console.WriteLine(f.Value);
}
}
$ ./foo.exe
29
There's a time and a place to do function chaining, and it's not "anytime and everywhere." But, LINQ is a good example of a place that hugely benefits from function chaining.
A class will often return an instance of itself from what is sometimes called a "factory" method. In Java or C++ (etc) this would usually be a public static method, e.g. you would call it directly on the class rather than on an instance of a class.
In your case, in Java, it might look something like this:
List<Change> changes = Change.getRecentChanges();
This assumes that the Change class itself knows how to track changes itself, rather than that job being the responsibility of some other object in the system.
A class can also return an instance of itself in the singleton pattern, where you want to ensure that only one instance of a class exists in the world:
Foo foo = Foo.getInstance();
The fluent interface methods work on the principal of returning an instance of itself, e.g.
StringBuilder sb = new StringBuilder("123");
sb.Append("456").Append("789");
You need to think about what you're trying to model. In your case, I would have a ChangeList class that contains one or more Change objects.
On the other hand, if you were modeling a hierarchical structure where a class can reference other instances of the class, then what you're doing makes sense. E.g. a tree node, which can contain other tree nodes.
Another common scenario is having the class implement a static method which returns an instance of it. That should be used when creating a new instance of the class.
I don't know of any design rule that says that's bad. So if in your model a single change can be composed of multiple changes go for it.