I tries some Unit Testing and ran into a problem of testing methods which use classes instances and not the interfaces. In that case I found that MS Moles can help me. But the it seems that they are not friendly with type casting situations. And I found no info and even no questions how to deal with this situation. Example:
public class ClassA
{
public int Number {get {return 10;}}
}
public class ClassB
{
public int Count1(ClassA arg) { return arg.Number; }
public int Count2(object arg) { return (arg as ClassA).Number; }
}
and while testing
var cl = new MolesUnitTesting.Moles.MClassA();
MolesUnitTesting.Moles.MClassA.AllInstances.NumberGet = t1 => 20;
The first Count
works just fine and returns 20 but casting in the second returns Null
. Is there any way to test such method without using interface and usual mocking? If there is other lib that can help me please provide me with it's name.
Instead of mocking all instances of the ClassA
type you can do the following:
var target = new MClassA();
target.NumberGet = () => 42;
Assert.AreEqual(Count1(target), 42);
Assert.AreEqual(Count2(target.Instance), 42);
Notice that for the Count1
you can use the mole directly because it will be automatically converted to a ClassA
instance. However, since Count2
receives an object
you need to be explicit and passed the target.Instance
which represents the moled ClassA
instance.
The reason Count1(target)
works is because the generated mole class MClassA
, which inherits from MoleBase<ClassA>
, defines the following implicit operator:
public static implicit operator ClassA(MoleBase<ClassA> mole) { // ... }