Rhino Mocks - Mocking a factory - rhino-mocks

I have a factory that creates job objects in the form of IJob
Public Interface IJobFactory
Function CreateJobs(ByVal cacheTypes As CacheTypes) As IEnumerable(Of IJob)
End Interface
The interface IJob defines three things
Public Interface IJob
Sub Execute()
ReadOnly Property Id() As Integer
ReadOnly Property JobType() As JobType
End Interface
I am trying to test the consumer of the factory, a class called JobManager. The job manager calles IJobFactory and asks for the collection of IJobs. I can stub that out just fine but I can't vary the collection size without a lot of work.
Is there a simple way to stub out the collection so that I get a range back?
How can I create a stub of IJobFactory.CreateJobs in such a way that I get back a collection of IJob stubs, say 5 or so where the Id of each of the IJob stubs is different. The ids could be 1 through 5 and that would work great.

I would do create a helper function to set expectations on the factory (c# notation, untested):
private List<IJob> SetExpectedJobs(MockRepository mocks, IJobFactory factory, int n)
{
List<IJob> result = new List<IJob>();
for(int i=1; i<=n; i++)
{
IJob job = mocks.CreateStub<IJob>();
Expect.Call(job.Id).Return(i).Repeat.Any();
result.Add(job);
}
Expect.Call(factory.CreateJobs(null)).Return(result).IgnoreArguments();
return result;
}
and call this function when you set expectation at the beginning of the test. Probably you should pass cacheTypes to this method as well.

Related

Make two factories return the same object that implements both interfaces

(I use C# in my examples, but this question is not specifically about C#.)
We have factories to create objects for multiple interfaces, one factory per interface.
Say we have a PrintingFactory to create an object implementing IPrinting and a ScanningFactory for IScanning. We have concrete printers implementing IPrinting and concrete scanners implementing IScanning and the factories decide which implementation is chosen.
In ScanningFactory I have:
public static IScanning Build()
{
...
return new CanonXYZ2000();
}
I have similar code in PrintingFactory, and in main I have:
scanner = ScanningFactory.Build();
printer = PrintingFactory.Build();
Now, what happens if I want to instantiate one object that implements both interfaces?
public class CanonXYZ2001MultiPurpose: IPrinting, IScanning {...}
I would like both factories to return the same object. How do I do this properly?
If i understand you correctly you are asking if CanonXYZ2001MultiPurpose can be created by both ScanningFactory and PrintingFactory ?
In this case both factories can return instances of CanonXYZ2001MultiPurpose with no issues, since this class implements both interfaces:
Scanning factory code:
public static IScanning Build()
{
...
return new CanonXYZ2001MultiPurpose ();
}
Printing factory code:
public static IPrinting Build()
{
...
return new CanonXYZ2001MultiPurpose ();
}
Both variables now hold instance of CanonXYZ2001MultiPurpose:
var scanner = ScanningFactory.Build();
var printer = PrintingFactory.Build();

VB.NET - Misusing instance variables?

Please take a look at the code below:
Public Class A
Public person1 As Person
End Class
Public Class B
Inherits A
Public Function CheckGender() As Boolean
If person1._Gender = "M" Then
CheckGender = True
End If
End Function
End Class
Public Class C
Inherits B
Public Function CheckAge() As Boolean
If person1._Age > 30 Then
CheckAge = True
End If
End Function
End Class
Public Class D
Inherits C
Public Sub SomeMethod()
Dim list As List(Of Person) = New List(Of Person)
Dim p1 As New Person("Ian", "M", 31)
Dim p2 As New Person("Susan", "F", 20)
Dim p3 As New Person("Mark", "M", 22)
list.Add(p1)
list.Add(p2)
list.Add(p3)
For Each Person As Person In list
person1 = Person
If CheckAge() And CheckGender() Then
'Do something
End If
Next
End Sub
Public Shared Sub Main()
Dim d As New D
d.SomeMethod()
End Sub
End Class
Public Class Person
Public _Name As String
Public _Gender As String
Public _Age As String
Public Sub New(ByVal Name As String, ByVal Gender As String, ByVal Age As Integer)
_Name = Name
_Gender = Gender
_Age = Age
End Sub
End Class
c.SomeMethod loops through three persons and does two checks: b.CheckGender and c.CheckAge. CheckGender and CheckAge use an instance variable from the superclass A.
The code in the live environment loops through 100,000 records daily in a database and deletes those where CheckGender and CheckAge are both true. Is it a bad design choice to use instance variables in this scenario? I was always taught to use local variables. I would expect the Person object to be passed to CheckGender and CheckAge on each loop. Or does it really not matter?
Please note that the above code is a hypothetical example. CheckGender and CheckAge are complex functions in the actual application.
As long as CheckGender and CheckAge are not accessing any private, protected or internal member of the classes in hierarchy, and are public functions, and their logic is the same for any instance, being A, B, or C, it is a better design to have these methods in another class. Make them static if possible. You can have them accept the most general implementation of your classes (A for instance) that allows checking either the age or gender. Taken from your code, you can even pass the Person property instead of using any of the A, B and C classes.
Use of inheritance in the above case and such logic is permitted though, as long as you need to do any or all of the following:
Conform to a specific interface or base class, that A, B and C classes have to implement/extend, and that interface or base class provides the CheckGender and CheckAge methods. This can be the only solution if you pass your objects to 3rd party API, that accepts the base class/interface as an argument and internally calls the check methods.
Here is example in C#:
public static class CheckUtil
{
public static bool CheckAgeOfPerson(Person p)
{
return p.Age > 30;
}
public static bool CheckAgeOfObject(A obj)
{
// NOTE: obj.person1 must be accessible - by being either public or internal.
// If this class is in another assembly, internal is not useful
return CheckAgeOfPerson(obj.person1);
}
}
A objA = ...;
B objB = ...;
C objC = ...;
CheckUtil.CheckAgeOfObject(objA);
CheckUtil.CheckAgeOfObject(objB);
CheckUtil.CheckAgeOfObject(objC);
CheckUtil.CheckAgeOfPerson(objA.person1);
CheckUtil.CheckAgeOfPerson(objB.person1);
CheckUtil.CheckAgeOfPerson(objC.person1);
Provide specific implementation to the classes. If you have to some logic in CheckAge for instances of A, but either completely different validation for instances of B, or a combination of the existing and some new logic in C, then inheritance is your friend. Still, if that is the case, I'd prefer exposing the CheckGender and CheckAge to interface and call them via the interface. That way, inheritance is valid, but not mandatory, as long the interface is satisfied.
here is an example in C#:
public interface IGenderCheckable
{
bool CheckGender();
}
public interface IAgeCheckable
{
bool CheckAge();
}
public class A : IAgeCheckable, IGenderCheckable
{
public virtual bool CheckGender()
{
return this.person1.Gender.Equals("M");
}
public virtual bool CheckAge()
{
return this.person1.Age > 30;
}
}
public class B : A
{
public override bool CheckAge()
{
// combine custom logic with new logic
return this.person1.Age < 0 || base.CheckAge();
}
}
For complex scenarios, a combination of both approaches might be also used (of course for far more complex cases than age and gender checks):
public class A : IAgeCheckable, IGenderCheckable
{
...
}
public static class CheckUtil
{
public static bool CheckAge(IAgeCheckable obj)
{
return obj.CheckAge();
}
public static bool CheckGender(IGenderCheckable)
{
return obj.CheckGender();
}
}
About usage of instance variables vs local variables - there is a drawback in performance of using instance variables in .NET especially when they are value types. Use of local member that is int _someIntMember for example gets translated to this._someIntMember - which in turn calls the heap to get the this object, and then accesses its _someIntMember member. Having the member as a local variable, puts its value in the stack, and reads it from there without the unnecessary roundtrip trough the heap. Moreover, the stack is faster than the heap.
However, I cannot say whether too much heap usage is an abuse of it, neither a misuse of local variables when they are used too much. This depends on the performance needed, and the complexity of code. Sometimes local variables make the code more-readable, but if too many, you could easily forget what each one was (and that can be more serious issue than the negligent performance gain). So it is a matter of style and necessity.
In case you're interested in "fixing" your code to make Person a Property rather than a field, change the implementation of Class A as follows:
Public Class A
Public Property Person1 As Person
Public Overridable Function ComputeAge() As Integer
Return Person1.Age
End Function
End Class
The benefit here is you have the ability to add additional abstractions over getting and setting this property down the road if you need to. The compiler will generate a hidden private backing field for the auto property. You would still access the Person1 from any implementing classes:
Public Class B
Inherits A
Public Overrides Function ComputeAge() As Integer
Return MyBase.Person1.Age.AddYears(1)
End Function
End Class

Autofac - Resolve specific implementation from registered assembly

I'm using Autofac and want to resolve the correct implementation of the current assembly
I have a DataContextFactory Interface and Class:
Public Interface IDataContextFactory
Inherits IDisposable
Function GetDataContext() As IDataContext
End Interface
and the Implementation of the Interface
Public Class CDataContextFactory
Implements IDataContextFactory
Private m_oDbContext As IDataContext
Public Sub New(ByVal i_oDbContext As IDataContext)
m_oDbContext = i_oDbContext
End Sub
Public Function GetDataContext() As CoreData.IDataContext Implements CoreData.IDataContextFactory.GetDataContext
Return m_oDbContext
End Function
End Class
So now I have in every registered assembly different IDataContext Implementations. For example I have an assembly called ReportData with the data context
Public Class CReportDataContext
Inherits DbContext
Implements IDataContext
---
End Class
And also one implementation inside an other Assembly CommonData
Public Class CFacadeDataContext
Implements IDataContext
---
End Class
Then I have in every Assembly an implementation of my IRepository. For example
Public MustInherit Class CBaseReadRepository(Of T As {IEntity, Class})
Implements IReadRepository(Of T)
Private m_oDataContextFactory As IDataContextFactory
Private m_oDataContext As IDataContext
Protected ReadOnly m_oObjectDataSet As CQuery(Of T)
Public Sub New(ByVal i_oDataContextFactory As IDataContextFactory)
m_oDataContextFactory = i_oDataContextFactory
m_oObjectDataSet = DataContext.ObjectDataSet(Of T)()
End Sub
----
End Class
So how can I solve that the DataContextFactory will resolve the CReportDataContext inside the Assembly ReportData and the CFacadeDataContext inside the Assembly CommonData
Here is my ContainerBuilder registration:
Dim builder As New ContainerBuilder()
Dim oData = Assembly.Load("ReportData")
builder.RegisterAssemblyTypes(oData).Where(Function(t) t.Name.EndsWith("DataContext")).As(Of IDataContext) _
.AsImplementedInterfaces.SingleInstance
oData = Assembly.Load("CommonData")
builder.RegisterAssemblyTypes(oData).Where(Function(t) t.Name.EndsWith("DataContext")) _
.AsImplementedInterfaces().SingleInstance
builder.RegisterAdapter(Of IDataContext, IDataContextFactory)(Function(x) New CDataContextFactory(x))
Thanks
Autofac doesn't have built-in support for this sort of use case. Generally it's recommended that you try not to tie specific implementations to consumers because that breaks the whole IoC pattern - you may as well "new-up" the dependency type you need right in the class rather than injecting it.
If you absolutely must tie them together, you only have a couple of options. Neither is pretty, and both will require you to change the way you register things - you may not be able to do the RegisterAssemblyTypes assembly scanning like you do now.
First, you could use named registrations. When you register your IDataContext, you give it a name. When you register your consuming class, you tell the builder which named instance you expect to use.
builder.RegisterType<MyDataContext>().Named<IDataContext>("some-name");
var contextParam = ResolvedParameter.ForNamed<IDataContext>("some-name");
builder.RegisterType<MyConsumer>().As<IConsumer>().WithParameter(contextParam);
Second, you could register an expression rather than a type for the consumer:
builder.Register(c => new Consumer(new SomeContext())).As<IConsumer>();
Finally, you could create a special module that does the work of figuring out which assembly the consumer is coming from and try to match it to a corresponding IDataContext. This is more "automatic" but is a lot more complex. A stub might look like this:
public class DataContextModule : Autofac.Module
{
protected override void AttachToComponentRegistration(
IComponentRegistry componentRegistry,
IComponentRegistration registration)
{
registration.Preparing += OnComponentPreparing;
}
public static void OnComponentPreparing(object sender, PreparingEventArgs e)
{
Type typeBeingResolved = e.Component.Activator.LimitType;
// TODO: Do some reflection to determine if the type takes an IDataContext
// in the constructor. If it doesn't, bail. If it does...
var parameter = new ResolvedParameter(
(p, i) => p.ParameterType = typeof(IDataContext),
(p, i) => {
// TODO: Use i (the IComponentContext for the resolution)
// to locate the right IDataContext from the list of registrations,
// resolve that one, and return it so it can be used in
// constructing the consumer object.
});
}
}
Like I said, not pretty.
If you have the ability to influence your design, it might be easier to make marker interfaces, like:
public interface ICoreDataContext : IDataContext { }
And then in your constructors take the specific interface:
public SomeClass(ICoreDataContext context);
That way type resolution would just work. (Marker interfaces aren't the greatest pattern in the world, either, but it's arguably better than tying individual implementations of things to specific consuming types.)

Factory method for generics in VB.NET

I want to create a factory for generic classes in VB.NET and I am running into issues.
What I have are two interfaces:
IPersistentObject and IPManagerBase(Of T as IPersistentObject)
The logic is that for each type of peristent object I have a corresponding manager class handling query logic.
Now I have a base class like this:
public class PManagerBase(Of T as IPersistentObject) Implements IPManagerBase(of T)
So, now in the real world I have a persistent type "PUser" and a corresponding manager declared like this:
public class PUserManager implements PManagerBase(Of PUser)
I have about 100 of those persistent objects and corresponding manager classes.
Now I want to have a factory, which I would invoke like this (removing the details):
MyFactory.CreateManager<PUserManager>()
I am creating my Factory like this
public class MyFactory
public shared function CreateManager(Of T as {PManagerBase(Of IPersistentObject), New}) as T
return new T()
end function
end class
Looks great.
Now I want to invoke it:
Dim myManager = MyFactory.CreateManager<PUserManager>()
What happens?
I get a compile error: "PUserManager does not implement/inherit PManagerBase(Of IPersistentObject)". I get the message in German so this is a free tranlation.
What would I need to change to make this running?
It works if I declare my factory like this:
public class MyFactory
public shared function CreateManager(Of T as {PManagerBase(Of PUser), New}) as T
return new T()
end function
end class
But then the benefit is gone, since it works only for Managers of the PUser object.
A better solution is
public class MyFactory
public shared function CreateManager(Of T as {PManagerBase(Of U), New}, U as IPersistentObject) as T
return new T()
end function
end class
This works, but I have to call my factory method like this now:
Dim myManager = MyFactory.CreateManager<PUserManager, PUser>()
I don't like this since this is redundant and I don't need U at all in the function. In it's declaration PUserManager is tied to PUser.
Is there a better way? Why is PUserManager not inheriting from PManagerBase(Of IPersistentObject)?
This is a problem with generics, if you are using VS 2010 you may want to take a look at covariance and contravariance and modify your IPManagerBase definition accordingly.

Ensuring only factory can create instance

class XFactory {
private XFactory() {}
static void getX() {
if(...)
return new A(new XFactory());
else
return new B(new XFactory());
}
}
class A {
private A() {}
public A(XFactory xf) {}
}
class B {
private B() {}
public A(XFactory xf) {}
}
By this way I can ensure only Factory can create instances of it's belonging Classes.
Is this right approach or there is any other alternative/good approach?
The common approach (in C++) is to make the "belonging classes" constructors private, and have them declare the factory class as friend.
I would make classes A and B friends of XFactory, and keep all their constructors private. Therefore, only XFactory has access to their constructors.
That is, in C++. In Java or C#, I don't see any clean way of enforcing that at compile-time. Your example is far from fool-proof and even a bit confusing, since as long as one has an instance of XFactory, he can pass it to the constructor of A or B and instantiate them directly like that.
If you were up for hacks and could not make your constructors private, you could:
Make your factory a global singleton and to create an object:
Create a random key
Add that key to a private list in the factory object of keys in use
Pass the key to the constructor
Have the constructor retrieve the global factory object and call it to validate the key.
If they key validation fails, scuttle your program (call exit, die, ... whatever is appropriate). Or possibly email a stack tract to an admin. This is the kind of thing that should be caught quickly.
(Do I get hack points?)
Jacob
In Java you can make the constructors private and provide the factory in the form of a public nested class, since nested classes have access to the private members of the class in which they are declared.
public class ExampleClass {
private ExampleClass() {
}
public class NestedFactory {
public ExampleClass createExample() {
return new ExampleClass();
}
}
Anyone who wanted to could create an instance of ExampleClass.NestedFactory and through it instantiate ExampleClasses.
I haven't been able to figure out a way to do this that lets you then inherit from ExampleClass since the Java compiler demands that you specify a constructor for the superclass... so that's a disadvantage.