check that property setter was called - rhino-mocks

I have a class I am unit testing and all I want to do is to verify that the public setter gets called on the property. Any ideas on how to do this?
I don't want to check that a value was set to prove that it was called. I only want to ensure that the constructor is using the public setter . Note that this property data type is a primitive string

This is not the sort of scenario that mocking is designed for because you are trying to test an implementation detail. Now if this property was on a different class that the original class accessed via an interface, you would mock that interface and set an expectation with the IgnoreArguments syntax:
public interface IMyInterface
{
string MyString { get; set; }
}
public class MyClass
{
public MyClass(IMyInterface argument)
{
argument.MyString = "foo";
}
}
[TestClass]
public class Tests
{
[TestMethod]
public void Test()
{
var mock = MockRepository.GenerateMock<IMyInterface>();
mock.Expect(m => m.MyString = "anything").IgnoreArguments();
new MyClass(mock);
mock.VerifyAllExpectations();
}
}
There are 2 problems with what you are trying to do. The first is that you are trying to mock a concrete class, so you can only set expectations if the properties are virtual.
The second problem is the fact that the event that you want to test occurs in the constructor, and therefore occurs when you create the mock, and so occurs before you can set any expectations.
If the class is not sealed, and the property is virtual, you can test this without mocks by creating your own derived class to test with such as this:
public class RealClass
{
public virtual string RealString { get; set; }
public RealClass()
{
RealString = "blah";
}
}
[TestClass]
public class Tests
{
private class MockClass : RealClass
{
public bool WasStringSet;
public override string RealString
{
set { WasStringSet = true; }
}
}
[TestMethod]
public void Test()
{
MockClass mockClass = new MockClass();
Assert.IsTrue(mockClass.WasStringSet);
}
}

Related

Why does ninject's constructorScorer rate constructors which have unresolvable params?

Given some simple classes and interfaces...
public interface IClass1 { }; public class Class1 : IClass1 { }
public interface IClass2 { }; public class Class2 : IClass2 { }
... this injectable code ...
public class Class3
{
public Class3(IClass1 class1, IClass2 class2)
{
}
public Class3(IClass1 class1)
{
}
}
... and this setup ...
static void Main(string[] args)
{
var kernel = new StandardKernel();
kernel.Bind<IClass1>().To<Class1>();
var instance = kernel.Get<IClass1>();
}
Ninject will crash declaring that it can't find a binding for IClass2.
On the one had this is understandable, because it doesn't have a binding for IClass2.
However it does have access to a constructor which does not require such a binding.
After some investigation, we have discovered that both of these constructors have the same 'score' because they both have the same number of resolvable parameters.
Ninject appears to treat them as equally valid. It picks the constructor which requires an IClass2 parameter because it is listed first within the code.
So if I reverse the order of these constructors thus...
public class Class3
{
public Class3(IClass1 class1)
{
}
public Class3(IClass1 class1, IClass2 class2)
{
}
}
... everything works.
My question is therefore....
Why is the constructor (the one requiring an IClass2 parameter) ever considered a valid contender when it has unresolvable parameters?

Setting a readonly "Parent" property in child object from parent

I am trying to reproduce the behaviour found in some WinForms controls (such as DataGridView and DataGridViewColumn) where the child object has a property pointing to the parent. This property is normally readonly, but it somehow changes after the parent's Add() method has been called.
In my code I have two classes, DataGroup and DataEntry, with the latter being the child object.
If I simply implemented something like:
public class DataEntry
{
public DataGroup Parent { get; set; }
}
public class DataGroup
{
public List<DataEntry> DataEntries { get; set; }
public DataGroup()
{
DataEntries = new List<DataEntry>();
}
public void Add(DataEntry de)
{
// Check stuff here
// ...
//
DataEntries.Add(de);
de.Parent = this;
}
}
it would certainly work, but with one major drawback: DataEntry.Parent has a public setter, so the property could be modified from anywhere without any of the checks I designed in DataGroup.Add()
I could maybe do the following:
public class DataEntry
{
private DataGroup _parent;
public DataGroup Parent
{
get { return _parent; }
set
{
_parent = value;
_parent.Add(this);
}
}
}
public class DataGroup
{
...
public void Add(DataEntry de)
{
// Check stuff here
// ...
//
_dataEntries.Add(de);
// de.Parent = this; Already set!
}
...
}
which would work fine in case I wanted to add the child by setting its parent property, but would not update DataEntry.Parent if I called DataGroup.Add()
As I already said, it is quite normal for WinForms controls not to be able to change the Parent property directly in the child, but the property is changed after the Add method is called from the parent.
I can't figure out the link, a way for the parent to modify a property in the child, unless that property is public or exposed through a method, both of which would grant a chance to bypass my checks and ultimately produce errors.
if you just want to hide the method from outside parties you could declare the method internal
internal void SetParent(DataGroup dg)
{
//code to set parent
}
I've never tried this but it might work also. I do it with private all the time.
public DataGroup Parent { get; internal set; }
Another option to hide it from yourself a little more is to have an Explicit Interface Implementation. and even combine it with internal to hide it from outside. When you Explicitly implement an interface the only way to call the method is to cast the object to the interface first. I think something like this would work
internal interface ISetParent
{
void SetParent(DataGroup dg);
}
public class DataEntry : ISetParent
{
void ISetParent.SetParent(DataGroup dg)
{
Parent = dg;
}
public DataGroup Parent { get; private set;}
}
public class DataGroup
{
public List<DataEntry> DataEntries { get; set; }
public DataGroup()
{
DataEntries = new List<DataEntry>();
}
public void Add(DataEntry de)
{
// Check stuff here
// ...
//
DataEntries.Add(de);
((ISetParent)de).SetParent(this);
}
}

How to design around lack of multiple inheritance?

Using interfaces won't work because I want a single implementation. Using this solution would end in a lot of redundant code because I plan on having quite a few sub classes (composition vs inheritance). I've decided that a problem-specific design solution is what I'm looking for, and I can't think of anything elegant.
Basically I want classes to have separate properties, and for those properties to be attached at design time to any sub class I choose. Say, I have class 'ninja'. I would like to be able to make arbitrary sub classes such as 'grayNinja' where a gray ninja will always have a sword and throwing stars. Then possibly 'redNinja' who will always have a sword and a cape. Obviously swords, stars, and capes will each have their own implementation - and this is where I can't use interfaces. The closest solution I could find was the decorator pattern, but I don't want that functionality at runtime. Is the best solution an offshoot of that? Where inside the Black Ninja class constructor, I pass it through the constructors of sword and throwingStar? (those being abstract classes)
haven't coded in a while and reading hasn't gotten me too far - forgive me if the answer is simple.
Edit: Answered my own question. I can't mark it as 'answer' until tomorrow. Please let me know if there's a problem with it that I didn't catch. All the reading this problem forced me to do has been awesome. Learned quite a bit.
You want classes to have separate properties. Have you considered coding exactly that?
For example, you want a RedNinja that is-a Ninja that has-a sword and cape. Okay, so define Ninja to have an inventory, make it accessible through Ninja, and pass in an inventory through RedNinja's constructor. You can do the same thing for behaviors.
I've done once a similar app. with a earlier "C++" compiler that supported only single inheritance and no interfaces, at all.
// base class for all ninjas
public class Ninja {
// default constructor
public Ninja() { ... }
// default destructor
public ~Ninja() { ... }
} // class
public class StarNinja: public Ninja {
// default constructor
public StarNinja() { ... }
// default destructor
public ~StarNinja() { ... }
public void throwStars() { ... }
} // class
public class KatannaNinja: public Ninja {
// default constructor
public KatannaNinja() { ... }
// default destructor
public ~KatannaNinja() { ... }
public void useKatanna() { ... }
} // class
public class InvisibleNinja: public Ninja {
// default constructor
public InvisibleNinja() { ... }
// default destructor
public ~InvisibleNinja() { ... }
public void becomeVisible() { ... }
public void becomeInvisible() { ... }
} // class
public class FlyNinja: public Ninja {
// default constructor
public FlyNinja() { ... }
// default destructor
public ~FlyNinja() { ... }
public void fly() { ... }
public void land() { ... }
} // class
public class InvincibleNinja: public Ninja {
// default constructor
public InvincibleNinja() { ... }
// default destructor
public ~InvincibleNinja() { ... }
public void turnToStone() { ... }
public void turnToHuman() { ... }
} // class
// --> this doesn't need to have the same superclass,
// --> but, it helps
public class SuperNinja: public Ninja {
StarNinja* LeftArm;
InvincibleNinja* RightArm;
FlyNinja* LeftLeg;
KatannaNinja* RightLeg;
InvisibleNinja* Body;
// default constructor
public SuperNinja() {
// -> there is no rule to call composed classes,
LeftArm = new StarNinja();
RightArm = new InvincibleNinja();
LeftLeg = new FlyNinja();
RightLeg = new KatannaNinja();
Body = new InvisibleNinja();
}
// default destructor
public ~SuperNinja() {
// -> there is no rule to call composed classes
delete LeftArm();
delete RightArm();
delete LeftLeg();
delete RightLeg();
delete Body();
}
// --> add all public methods from peers,
// --> to main class
public void throwStars() { LeftArm->throwStars(); }
public void useKatanna() { RightLeg->useKatanna(); }
public void becomeVisible() { Body->becomeVisible() }
public void becomeInvisible() { Body->becomeInvisible() }
public void fly() { LeftLeg->fly() }
public void land() { LeftLeg->land() }
public void turnToStone() { RightArm->turnToStone(); }
public void turnToHuman() { RightArm->turnToHuman(); }
} // class
Im afraid, that the most close example is the composition design pattern. In order, to become more similar to inheritance, I make a generic base class that all composite classes share, and I make a main class that will be the result of the multiple inheritance, that has a copy of all the public methods of the component classes.
If you want to use interfaces, to enforce that main class have all important methods,
then make an interface that matches each composing class, and implemented in the main class.
public interface INinja {
public void NinjaScream() { ... }
} // class
public interface IStarNinja {
void throwStars();
} // class
public interface IKatannaNinja {
void useKatanna();
} // class
public interface IInvisibleNinja {
void becomeVisible();
void becomeInvisible();
} // class
public interface CFlyNinja {
void fly();
void land();
} // class
public interface IInvincibleNinja {
void turnToStone() { ... }
void turnToHuman() { ... }
} // class
// base class for all ninjas
public class CNinja: public INinja {
// default constructor
public CNinja() { ... }
// default destructor
public ~CNinja() { ... }
public void NinjaScream() { ... }
} // class
public class CStarNinja: public CNinja, INinja {
// default constructor
public CStarNinja() { ... }
// default destructor
public ~CStarNinja() { ... }
public void NinjaScream() { ... }
public void throwStars() { ... }
} // class
public class CKatannaNinja: public CNinja, IKatannaNinja {
// default constructor
public CKatannaNinja() { ... }
// default destructor
public ~CKatannaNinja() { ... }
public void NinjaScream() { ... }
public void useKatanna() { ... }
} // class
public class CInvisibleNinja: public CNinja, IInvisibleNinja {
// default constructor
public CInvisibleNinja() { ... }
// default destructor
public ~CInvisibleNinja() { ... }
public void becomeVisible() { ... }
public void becomeInvisible() { ... }
} // class
public class CFlyNinja: public CNinja, IFlyNinja {
// default constructor
public CFlyNinja() { ... }
// default destructor
public ~CFlyNinja() { ... }
public void fly() { ... }
public void land() { ... }
} // class
public class CInvincibleNinja: public CNinja, IInvincibleNinja {
// default constructor
public CInvincibleNinja() { ... }
// default destructor
public ~CInvincibleNinja() { ... }
public void turnToStone() { ... }
public void turnToHuman() { ... }
} // class
// --> this doesn't need to have the same superclass,
// --> but, it helps
public class CSuperNinja: public CNinja,
IKatannaNinja,
IInvisibleNinja,
IFlyNinja,
IInvincibleNinja
{
CStarNinja* LeftArm;
CInvincibleNinja* RightArm;
CFlyNinja* LeftLeg;
CKatannaNinja* RightLeg;
CInvisibleNinja* Body;
// default constructor
public CSuperNinja() {
// -> there is no rule to call composed classes
LeftArm = new CStarNinja();
RightArm = new CInvincibleNinja();
LeftLeg = new CFlyNinja();
RightLeg = new CKatannaNinja();
Body = new CInvisibleNinja();
}
// default destructor
public ~SuperNinja() {
// -> there is no rule to call composed classes
delete LeftArm();
delete RightArm();
delete LeftLeg();
delete RightLeg();
delete Body();
}
// --> add all public methods from peers,
// --> to main class
public void throwStars() { LeftArm->throwStars(); }
public void useKatanna() { RightLeg->useKatanna(); }
public void becomeVisible() { Body->becomeVisible() }
public void becomeInvisible() { Body->becomeInvisible() }
public void fly() { LeftLeg->fly() }
public void land() { LeftLeg->land() }
public void turnToStone() { RightArm->turnToStone(); }
public void turnToHuman() { RightArm->turnToHuman(); }
} // class
I know this solution is complex, but, seems that there is not another way.
Cheers.
Alright so mix-ins through extension methods are going to be my preferred route. I couldn't figure out how to use dynamic proxies in vb.net (seemed to require libraries with lots of documentation that didn't cover specifically what I needed). Dynamic proxies also seems to be a bit dirtier of a solution than using extension methods. Composition would have been what I defaulted to if the previous two didn't work.
So one problem with extension methods, is that the code gets a little dirtier if you want to hold variables. Not much though. Another problem is that all the extension methods must be defined in modules, so the code might look a little goofy to a new eye. I will solve this by defining my interface and module with the corresponding extension method in the same file.
finally, here's some sample vb.net code if you don't want to see a full fledged example through the link.
Imports System.Runtime.CompilerServices 'for extension methods
Public Interface ISword
End Interface
Public Interface IThrowingStar
End Interface
Module ExtensionMethods
<Extension()>
Public Sub swingSword(ByVal hasASword As ISword)
Console.WriteLine("Sword has been swung")
End Sub
<Extension()>
Public Sub throwStar(ByVal hasAStar As IThrowingStar)
Console.WriteLine("Star has been thrown")
End Sub
End Module
Public Class RedNinja
Inherits Ninja
Implements IThrowingStar, ISword
Public Sub New()
End Sub
End Class
Public MustInherit Class Ninja
private curHealth as Integer
Public Sub New()
curHealth = 100
End Sub
Public Function getHP() As Integer
Return curHealth
End Function
End Class
Module Module1
Sub main()
Console.WriteLine("Type any character to continue.")
Console.ReadKey()
Dim a As New RedNinja
a.swingSword() 'prints "Sword has been swung"
a.throwStar() 'prints "Star has been thrown"
Console.WriteLine("End of program - Type any key to exit")
Console.ReadKey()
End Sub
End Module
Dirty solution, if you simply must have multiple inheritance, is using something like dynamic proxies in Java.
But I guess you're probably programming in C#, and this is language agnostic question, so here goes language agnostic answer: check out composite and factory design patterns, that should give you some ideas.
Also, it might not be needed to pass everything in constructor. Check out IoC pattern as well.

Autofac: how do I pass a reference to the component being resolved to one of its dependents?

With the following:
public class AClass
{
public ADependent Dependent { get; set; }
}
public class ADependent
{
public ADependent(AClass ownerValue) {}
}
with the following registrations...
builder.RegisterType<AClass>().PropertiesAutowired().InstancePerDependency();
builder.RegisterType<ADependent>().PropertiesAutowired().InstancePerDependency();
When I resolve an AClass, how do I make sure that 'ownerValue' is the instance of AClass being resolved, and not another instance? Thx
FOLLOW ON
The example above doesn't really catch the problem properly, which is how to wire up ADependent when registering when scanning... for example
public class AClass : IAClass
{
public IADependent Dependent { get; set; }
}
public class ADependent : IADependent
{
public ADependent(IAClass ownerValue) {}
}
// registrations...
builder.RegisterAssemblyTypes(assemblies)
.AssignableTo<IAClass>()
.As<IAClass>()
.InstancePerDependency()
.PropertiesAutowired();
builder.RegisterAssemblyTypes(assemblies)
.AssignableTo<IADependent>()
.As<IADependent>()
.InstancePerDependency()
.PropertiesAutowired();
The function I am looking for really is another relationship type like
public class ADependent : IADependent
{
public ADependent(OwnedBy<IAClass> ownerValue) {}
}
The OwnedBy indicates that ownerValue is the instance that caused ADependent to created. Does something like this make sense? It would certainly make wiring up UI components a breeze.
To extend Steven's approach, you can even Resolve() the second class, passing the first instance as a parameter:
builder.RegisterType<ADependent>();
builder.Register<AClass>(c =>
{
var a = new AClass();
a.Dependent = c.Resolve<ADependent>(TypedParameter.From(a));
return a;
});
You can register a lambda to do the trick:
builder.Register<AClass>(_ =>
{
var a = new AClass();
a.Dependent = new ADependent(a);
return a;
});

Ninject Cascading Inection with IList

I am trying to use Ninject to implement cascading injection into a class that contains an IList field. It seems that, unless I specifically specify each binding to use in the kernel.Get method, the IList property is always injected with a list of a single default object.
The following VSTest code illustrates the problem. The first test fails because the IList field contains one MyType object with Name=null. The second test passes, but I had to specifically tell Ninject what constructor arguments to use. I am using the latest build from the ninject.web.mvc project for MVC 3.
Does Ninject specifically treat IList different, or is there a better way to handle this? Note that this seems to only be a problem when using an IList. Createing a custom collection object that wraps IList works as expected in the first test.
[TestClass()]
public class NinjectTest
{
[TestMethod()]
public void ListTest_Fails_NameNullAndCountIncorrect()
{
var kernel = new Ninject.StandardKernel(new MyNinjectModule());
var target = kernel.Get<MyModel>();
var actual = target.GetList();
// Fails. Returned value is set to a list of a single object equal to default(MyType)
Assert.AreEqual(2, actual.Count());
// Fails because MyType object is initialized with a null "Name" property
Assert.AreEqual("Fred", actual.First().Name);
}
[TestMethod()]
public void ListTest_Passes_SeemsLikeUnnecessaryConfiguration()
{
var kernel = new Ninject.StandardKernel(new MyNinjectModule());
var target = kernel.Get<MyModel>(new ConstructorArgument("myGenericObject", kernel.Get<IGenericObject<MyType>>(new ConstructorArgument("myList", kernel.Get<IList<MyType>>()))));
var actual = target.GetList();
Assert.AreEqual(2, actual.Count());
Assert.AreEqual("Fred", actual.First().Name);
}
}
public class MyNinjectModule : NinjectModule
{
public override void Load()
{
Bind<IList<MyType>>().ToConstant(new List<MyType> { new MyType { Name = "Fred" }, new MyType { Name = "Bob" } });
Bind<IGenericObject<MyType>>().To<StubObject<MyType>>();
}
}
public class MyModel
{
private IGenericObject<MyType> myGenericObject;
public MyModel(IGenericObject<MyType> myGenericObject)
{
this.myGenericObject = myGenericObject;
}
public IEnumerable<MyType> GetList()
{
return myGenericObject.GetList();
}
}
public interface IGenericObject<T>
{
IList<T> GetList();
}
public class StubObject<T> : IGenericObject<T>
{
private IList<T> _myList;
public StubObject(IList<T> myList)
{
_myList = myList;
}
public IList<T> GetList()
{
return _myList;
}
}
public class MyType
{
public String Name { get; set; }
}
lists, collections and arrays are handled slightly different. For those types ninject will inject a list or array containing an instance of all bindings for the generic type. In your case the implementation type is a class which is aoutobound by default. So the list will contain one instance of that class. If you add an interface to that class and use this one the list will be empty.