Avoiding instance construction of return type while generating stub for method - rhino-mocks

I have issue while trying to mock method that returns instance of abstract class with Rhino Mocks. Issue is that MammalBase constructor is invoked while stub is created and I would like to avoid that. All source code in question is locked for editing and only tests can be changed.
Eventually, base class is processing something by type attributes in constructor, and throws exception if no adequate attributes are detected. That causes a extensive logging.
My hope is to remove unnecessary logs from tests.
Is it possible to instruct Rhino Mocks not to instantiate return type (MammalBase) when it creates proxy while creating a stub?
Is explicit attribute or type setting possible for return value while Rhino creates stub for method with abstract class instance as return type?
Is avoiding constructor even possible without making stubbed method return interface?
I found that issue does not exist if:
1. Stubbed method returns array like MammalBase[],
2. Stubbed method returns derivate class like "Human" first, since no more constructors of base class are invoked.
Thanks in advance!
(Code sample)
public interface IDetermineMammalByType
{
MammalBase DetermineMammalByType(MammalBase creature);
}
public abstract class MammalBase
{
protected MammalBase()
{
CustomAttribute[] attributes = (CustomAttribute[])Attribute.GetCustomAttributes(this.GetType(), typeof(CustomAttribute));
if (!attributes.Any(x=> x as CustomAttribute != null))
{
//This causes issue
throw new Exception();
}
}
}
[CustomAttribute()]
public class Human : MammalBase { }
[System.AttributeUsage(System.AttributeTargets.Class |
System.AttributeTargets.Struct)]
public class CustomAttribute : System.Attribute
{
public CustomAttribute() { }
}
public class MammalDetector : IDetermineMammalByType
{
public MammalBase DetermineMammalByType(MammalBase creature)
{
//Some logic
return null;
}
}
//TEST
[TestMethod()]
public void DetermineMammalByTypeTest()
{
IDetermineMammalByType myTest = MockRepository.GenerateStub<IDetermineMammalByType>();
var creature = new Human();
//Here it fails while mocking method
myTest.Stub(x => x.DetermineMammalByType(creature)).Return(new Human());
}

Related

Verifications involving non-mocked class with mocked abstract parent

A member of my team has written a JMockit-based test method that using a Verifications instance to assert a method was invoked on the UUT, which is not mocked, but extends a mocked abstract parent (it happens to be a Hibernate repository). The test passes, but my opinion, based on the JMockit documentation, is that only mocks should be used in a Verifications instance initializer. I think the result is a false negative but my team member insists it's a valid verification call. The test itself is simple, so I've recreated it using contrived objects:
package com.acme.dataacess;
public abstract class AbstractRepository {
public final T list(Class<T> clazz, final Collection<String> keys) {
.....
}
}
package com.acme.module.dataacess
public class FooRepository extends AbstractRepository<Foo> {
public List<Foo> list() {
return getFoos(null);
}
public List<Foo> list(Collection<String> keys) {
return list(Foo.class, keys);
}
}
public class FooRepositoryTest {
#Tested
private FooRepository uut;
#Mocked
private AbstractRepository mockAbstractRepository;
#Test
public void testFoo1() {
// Execute the test.
this.uut.list(null);
// Verify the results.
new Verifications() {
{
// I don't think this is a valid verification, because the goal
// of the test is to assert a delegated method in a non-mocked
// class was invoked.
uut.list(null);
}
};
}
}
Is this a valid JMockit verification?

Simpleinjctor get instance based on generic type

I need to convert Ninject to SimpleInjector Implementation.
I have the following code
public T Resolve<T>()
{
// IKernel kernel - is the global declaration
return kernel.Get<T>();
}
I want the equivalent to this for simple injector
I have tried
public T Resolve<T>()
{
// SimpleInjector.Container kernel - is the global declaration
return kernel.GetInstance<T>();
}
But this throws an error due to T not being a class as it is a generic type.
I can't cast the method to strictly take and return T as class because it is an interface implementation.
Any Advice?
Either add a generic type constraint to your Resolve method:
public T Resolve<T>() where T : class
{
return kernel.GetInstance<T>();
}
or call the non-generic GetInstance overload:
public T Resolve<T>()
{
return (T)kernel.GetInstance(typeof(T));
}

Why can't I use Get<ClassNameOfConcreteInstance> as a method name in Ninject Extension Factory?

Look at this very simple example: Calling CreateCar it works, calling GetCar it fails, saying "Error activating ICar: No matching bindings are available, and the type is not self-bindable".
public interface ICar { }
public class Car : ICar
{
public Car(string carType) { }
}
public interface ICarFactory
{
ICar CreateCar(string carType); // this is fine
ICar GetCar(string carType); // this is bad
}
public class CarModule : NinjectModule
{
public override void Load()
{
Bind<ICarFactory>().ToFactory();
Bind<ICar>().To<Car>();
}
}
public class Program
{
public static void Main()
{
using (var kernel = new StandardKernel(new FuncModule(), new CarModule()))
{
var factory = kernel.Get<ICarFactory>();
var car1 = factory.CreateCar("a type");
var car2 = factory.GetCar("another type");
}
}
}
Is assume it must be related to some kind of convention with Get*ClassName* (something like the NamedLikeFactoryMethod stuff). Is there any way to avoid this convention to be applied? I don't need it and I don't want it (I already wasted too much time trying to figure out why the binding was failing, it was just luck that I made a typo in 1 of my 10 factories and I noticed it to work just because the factory method name was "Ger" instead of "Get").
Thanks!
Yes, there is a convention, where the Get is used to obtain instances using a named binding. The factory extension generates code for you so you don't have to create boilerplate code for factories. You don't need to use it, if you don't want to.
But if you do, you are bound to its conventions. Use Create to build instances and Get to retrieve instances via a named binding.
All this is documented in the wiki.

Ninject factory method with input parameter to determine which implementation to return

I am trying to find a way to have a factory class / method that would take in an object or some kind of identifier (string or type) then based off the input parameter determine which implementation of the interface to create and return.
how do I setup my factory method and register the dependency for the interface? following is what I have roughly.
public class ISampleFactory
{
public ISample GetSample(Type type)
{
// do something here to return an implementation of ISample
}
}
public class SampleA : ISample
{
public void DoSomething();
}
public class SampleB : ISample
{
public void DoSomething();
}
public interface ISample
{
void DoSomethin();
}
Have a look at ninject Contextual Bindings Documentation:
You can either use Named Bindings:
this.Bind<ISample>().To<SampleA>().Named("A");
this.Bind<ISample>().To<SampleB>().Named("B");
or a conditional binding with any of the already available extensions or write your own:
this.Bind<ISample>().To<SampleA>().When(...);
this.Bind<ISample>().To<SampleB>().When(...);
see https://github.com/ninject/ninject/wiki/Contextual-Binding

Prevent Ninject from calling Initialize multiple times when binding to several interfaces

We have a concrete singleton service which implements Ninject.IInitializable and 2 interfaces. Problem is that services Initialize-methdod is called 2 times, when only one is desired. We are using .NET 3.5 and Ninject 2.0.0.0.
Is there a pattern in Ninject prevent this from happening. Neither of the interfaces implement Ninject.IInitializable. the service class is:
public class ConcreteService : IService1, IService2, Ninject.IInitializable
{
public void Initialize()
{
// This is called twice!
}
}
And module looks like this:
public class ServiceModule : NinjectModule
{
public override void Load()
{
this.Singleton<Iservice1, Iservice2, ConcreteService>();
}
}
where Singleton is an extension method defined like this:
public static void Singleton<K, T>(this NinjectModule module) where T : K
{
module.Bind<K>().To<T>().InSingletonScope();
}
public static void Singleton<K, L, T>(this NinjectModule module)
where T : K, L
{
Singleton<K, T>(module);
module.Bind<L>().ToMethod(n => n.Kernel.Get<T>());
}
Of course we could add bool initialized-member to ConcreteService and initialize only when it is false, but it seems quite a bit of a hack. And it would require repeating the same logic in every service that implements two or more interfaces.
Thanks for all the answers! I learned something from all of them! (I am having a hard time to decide which one mark correct).
We ended up creating IActivable interface and extending ninject kernel (it also removed nicely code level dependencies to ninject, allthough attributes still remain).
Ninject 3
Ninject 3.0 now supports multiple generic types in the call to bind, what you are trying to do can be easily accomplished in a single chained statement.
kernel.Bind<IService1, IService2>()
.To<ConcreteService>()
.InSingletonScope();
Ninject 2
You are setting up two different bindings K=>T and L=>T. Requesting instances of L will return transient instances of T. Requesting K will return a singleton instance of T.
In Ninject 2.0, an objects scope is per service interface bound to a scope callback.
When you have
Bind<IFoo>...InSingletonScope();
Bind<IBar>...InSingletonScope();
you are creating two different scopes.
You are saying
"Binding to IFoo will resolve to the same object that was returned
when .Get was called."
and
"Binding to IBar will resolve to the same object that was returned
when .Get was called."
you can chain the bindings together, but you will need to remove IInitializable as it will cause duplicate initialization when the instance is activated:
kernel.Bind<IBoo>()
.To<Foo>()
.InSingletonScope();
.OnActivation(instance=>instance.Initialize());
kernel.Bind<IBaz>()
.ToMethod( ctx => (IBaz) ctx.Kernel.Get<IBoo>() );
or
kernel.Bind<Foo>().ToSelf().InSingletonScope()
.OnActivation(instance=>instance.Initialize());
kernel.Bind<IBaz>().ToMethod( ctx => ctx.Kernel.Get<Foo>() );
kernel.Bind<IBoo>().ToMethod( ctx => ctx.Kernel.Get<Foo>() );
in order to get multiple interfaces to resolve to the same singleton instance. When I see situations like this, I always have to ask, is your object doing too much if you have a singleton with two responsibilities?
Update : Pretty sure using V3's multiple Bind overloads will address this; See this Q/A
Good question.
From looking at the source, the initialize bit happens after each Activate. Your Bind...ToMethod counts as one too. The strategy is pretty uniformly applied - there's no way to opt out in particular cases.
Your workaround options are to use an explicit OnActivation in your Bind which will do it conditionally (but to do that in a general way would require maintaining a Set of initialized objects (havent looked to see if there is a mechanism to stash a flag against an activated object)), or to make your Initialize idempotent through whatever means is cleanest for you.
EDIT:
internal interface IService1
{
}
internal interface IService2
{
}
public class ConcreteService : IService1, IService2, Ninject.IInitializable
{
public int CallCount { get; private set; }
public void Initialize()
{
++CallCount;
}
}
public class ServiceModule : NinjectModule
{
public override void Load()
{
this.Singleton<IService1, IService2, ConcreteService>();
}
}
Given the following helpers:
static class Helpers
{
public static void Singleton<K, T>( this NinjectModule module ) where T : K
{
module.Bind<K>().To<T>().InSingletonScope();
}
public static void Singleton<K, L, T>( this NinjectModule module )
where T : K, L
{
Singleton<T, T>( module );
module.Bind<K>().ToMethod( n => n.Kernel.Get<T>() );
module.Bind<L>().ToMethod( n => n.Kernel.Get<T>() );
}
}
#Ian Davis et al. The problem is that:
class Problem
{
[Fact]
static void x()
{
var kernel = new StandardKernel( new ServiceModule() );
var v1 = kernel.Get<IService1>();
var v2 = kernel.Get<IService2>();
var service = kernel.Get<ConcreteService>();
Console.WriteLine( service.CallCount ); // 3
Assert.AreEqual( 1, service.CallCount ); // FAILS
}
}
Because each activation (per Bind) initialises each time.
EDIT 2: Same when you use the following slightly more stripped down version:
static class Helpers
{
public static void Singleton<K, L, T>( this NinjectModule module )
where T : K, L
{
module.Bind<T>().ToSelf().InSingletonScope();
module.Bind<K>().ToMethod( n => n.Kernel.Get<T>() );
module.Bind<L>().ToMethod( n => n.Kernel.Get<T>() );
}
}
I think one of the option is, you create the object your self in the module and bind your object the each of the interfaces.
BTW, try not to use any container specific code in your production code. If you have to do that, use some helper and isolate them in the module project.
public class ServiceModule : NinjectModule
{
public override void Load()
{
ConcreteService svc = new ConcreteService();
Bind<IService1>().ToConstant(svc);
Bind<IService2>().ToConstant(svc);
....
}
}