I'm new to using a Mocking framework to mock objects for unit testing. I'm currently using Rhino Mocks and I would think it would have a method to do what I'm not finding it. Here is a LinqPad program (just copy and paste it in a C# program query and it will just work) that shows what I'm trying to do:
public interface MyTest{
int A(int i);
string B(int i);
}
/// This is an actual class that is a black box to me.
public class ActualClass : MyTest {
public int A(int i){
// Does some work
return ++i;
}
public string B(int i){
return A(i).ToString();
}
}
/// I'd like to create a mocked class that uses an instance of the actual class
/// to provide all of the implementations for the interface except for a single method
/// where I can check the parameter values, and provide my own return value,
/// or just call the actual class
public class MockedClass : MyTest {
private ActualClass _actual;
public MockedClass(ActualClass actual){
_actual = actual;
}
public int A(int i){
if(i == 1){
return 10;
}else{
return _actual.A(i);
}
}
public string B(int i){
return _actual.B(i);
}
}
void Main()
{
var mock = new MockedClass(new ActualClass());
mock.A(0).Dump();
mock.A(1).Dump();
mock.A(2).Dump();
mock.B(0).Dump();
mock.B(1).Dump();
mock.B(2).Dump();
}
Results:
1
10
3
1
2
3
What do I do to mock this out for unit testing. Do I need some sort of Dependency Injector?
Yes, you can change the return value of a mocked object based on the parameters passed in. I wouldn't take the approach of mixing a real dependency and a mocked dependency -- too much opportunity for a bug in the real dependency to creep in to your testing.
Here's an example you could use on your MyTest interface that examines the input argument of the mocked method and sets a return value accordingly:
var mock = MockRepository.GenerateStub<MyTest>();
mock.Stub(m => m.A(Arg<int>.Is.Anything))
.Return(99)
.WhenCalled(mi =>
{
var arg = Convert.ToInt32(mi.Arguments[0]);
switch (arg)
{
case 0:
mi.ReturnValue = 10;
break;
case 1:
mi.ReturnValue = 20;
break;
case 2:
mi.ReturnValue = 30;
break;
default:
mi.ReturnValue = -1;
break;
}
});
Note that the "Return(99)" is needed because when you stub a method that returns a value, Rhino.Mocks requires that you either define an exception to be thrown or define a return value. Even though we don't use the return value (since we provide our own inside the WhenCalled handler), it still must be defined or Rhino.Mocks will thrown an exception the first time the stub is called.
Related
Driver code
//---------------- Main.hx ------------------------------------------------------------------
import core.reflection.ReflectionTools;
import core.SomeClass;
class Main{
public static function main(){
var s = new SomeClass();
ReflectionTools.info(s);
}
}
The macro
//---------------- ReflectionTools.hx -----------------------------------------------------
class RelectionTools {
public static macro function info(obj:Expr):Expr{
var pos = Context.currentPos();
var block = [];
var result:Dynamic;
var type:Type=Context.typeof(obj);
result=(switch(type){
case TInst(t, params):new RelectionClass(t, params);
case TEnum(t, params):new ReflectionEnum(t, params);
case TDynamic(t):new ReflectionDynamic(t);
case TFun(args, ret):new ReflectionFunction(args, ret);
case TMono(t):new ReflectionMonomorph(t);
case TLazy(f):new ReflectionLazy(f);
case TAbstract(t, params):new ReflectionAbstract(t, params);
case TType(t, params):new ReflectionTypeDefinition(t, params);
case TAnonymous(a):new ReflectionAnonymousStructure(a);
});
return $v{result};
}
}
Haxe Compiler:
Expected Expr but got core.reflection.RelectionClass (see dump/decoding_error.txt for details)
It is not a build macro (which allows returning class instances) but it is an expression macro. The best way to mimic class functionality is with abstracts.
/* Solution Description
1. a custom Json abstract with underlying type {} and with implicit
casts to underlying type. See Json.hx
2. abstracts which reflect possible Type enums with underlying custom
Json abstract and forwards. See example ReflectionPrimitive.hx
and mimic inheritance by underlying types as superclass
see example ReflectionFunction.hx
3. uses same instantiation code as original class instantiation
but now they are abstracts (see PROBLEM(The macro). Solved! */
Step 1.a custom Json abstract with underlying type {} and with implicit casts to
underlying type.
// ---------------- Json.hx ----------------------------------------------
package core.ds.json;
import haxe.Serializer;
import haxe.Unserializer;
import haxe.Json as J;
abstract Json({}) from ({}) to ({}) {
public inline function new(?data:{}){
this=data;
if(this==null){
this={};
}
}
#:arrayAccess
public inline function get(key:String):Dynamic{
if(exists(key)){
return Reflect.field(this,key);
}
return null;
}
#:arrayAccess
public inline function set(key:String, value:Dynamic):Dynamic{
Reflect.setField(this, key, value);
return value;
}
public inline function isEmpty(key:String):Bool{
return !isSet(key) || (exists(key) && ( get(key)=="" || get(key)==''|| get(key)==null || get(key)==0 ));
}
public inline function isSet(key:String):Bool{
return exists(key) && get(key)!=null;
}
public inline function exists(key:String):Bool {
return Reflect.hasField(this, key);
}
#:to
public inline function toMap():Map<String, Dynamic>{
var result:Map<String, Dynamic>=new Map<String, Dynamic>();
var fields:Array<String>=Reflect.fields(this);
for (f in fields){
result.set(f, Reflect.field(this, f));
}
return result;
}
#:to
public inline function toJsonString():String{
return J.stringify(this,null," ");
}
public inline function values():Array<Dynamic>{
var result:Array<Dynamic>=[];
var keys:Array<String>=keys();
for(k in keys){
result.push(Reflect.field(this,k));
}
return result;
}
public inline function keys():Array<String>{
return Reflect.fields(this);
}
public inline function clone():Json{
return Unserializer.run(Serializer.run(this));
}
public var length(get,never):Int;
private inline function get_length():Int{
return keys().length;
}
public inline function keyValueIterator():KeyValueIterator<String, Dynamic>{
return toMap().keyValueIterator();
}
#:from
public static function fromJsonString(json:String):Json{
return J.parse(json);
}
#:from
public static function fromMap(map:Map<String, Dynamic>):Json{
var result={};
for (k=>v in map){
Reflect.setField(result, k, v);
}
return result;
}
}
Step 2. abstracts which reflect possible Type enums with underlying custom Json abstract and forwards. See example ReflectionPrimitive.hx and mimic inheritance by underlying types as superclass see example ReflectionFunction.hx
//---------------- ReflectionPrimitive.hx ----------------------------------------------
#:forward()
abstract ReflectionPrimitive(core.ds.json.Json) from core.ds.json.Json to core.ds.json.Json{
public inline function new(nameType:String){
this=new core.ds.json.Json({data:new core.ds.json.Json(), info:new core.ds.json.Json({nameType:nameType})});
}
public var data(get, set):core.ds.json.Json;
public var info(get, set):core.ds.json.Json;
private function get_data():core.ds.json.Json {
return this["data"];
}
private function set_data(value:core.ds.json.Json):core.ds.json.Json {
this["data"]=value;
return this;
}
private function get_info():core.ds.json.Json {
return this["info"];
}
private function set_info(value:core.ds.json.Json):core.ds.json.Json {
this["info"]=value;
return this;
}
}
Mimmicking inheritance
//---------------- ReflectionFunction.hx ----------------------------------------------
#:forward(data, info, get, isEmpty, isSet, exists, toMap, toJsonString, values, keys, clone, length, keyValueIterator, fromJsonString, fromMap)
abstract ReflectionFunction(ReflectionPrimitive) from ReflectionPrimitive to ReflectionPrimitive{
public inline function new(args:Array<{t:Type, opt:Bool, name:String}>, ret:Type){
this=new ReflectionPrimitive(NameType.FUNCTION);
var newArgs=new Array<core.ds.json.Json>();
for(a in args){
newArgs.push(new core.ds.json.Json(a));
}
this.data=this.data.set("args",newArgs).set("ret", ret);
}
public var args(get, never):Array<core.ds.json.Json>;
public var ret(get,never):Type;
private function get_args():Array<core.ds.json.Json>{
return this.data.get("args");
}
private function get_ret():Type{
return this.data.get("ret");
}
}
Leave the macro untouched it will work now.
Macro is a compile time feature, not runtime feature, you can't return class instance. Instead, you have to return expression which creates a new instance (I don't have your classes, so I use here my class)
var type=Context.typeof(obj);
return (switch(type){
case TInst(t, params):macro new MyClass();//RelectionClass(t, params);
case TEnum(t, params):macro new MyClass();//ReflectionEnum(t, params);
case TDynamic(t):macro new MyClass();//ReflectionDynamic(t);
case TFun(args, ret):macro new MyClass();//ReflectionFunction(args, ret);
case TMono(t):macro new MyClass();//ReflectionMonomorph(t);
case TLazy(f):macro new MyClass();//ReflectionLazy(f);
case TAbstract(t, params):macro new MyClass();//ReflectionAbstract(t, params);
case TType(t, params):macro new MyClass();//ReflectionTypeDefinition(t, params);
case TAnonymous(a):macro new MyClass();//ReflectionAnonymousStructure(a);
});
return macro null;
I have a piece of code below where Employee class creates object of AppraisalCalculator using reflection. I want to mock this AppraisalCalculator object using PowerMockito.
class AppraisalCalculator {
public int appraisal() {
return 300;
}
}
class Employee {
public int updateSalary() {
// line 1
AppraisalCalculator ac =
AppraisalCalculator.class.getConstructor().newInstance();
return ac.appraisal();
}
}
class TestRunner {
#Test
public void test() {
AppraisalCalulator acMock=PowerMockito.mock(AppraisalCalculator.class);
PowerMockito
.whenNew(AppraisalCalculator.class)
.withNoArguments()
.thenReturn(600);
Employee emp = new Employee();
int actualValue = emp.updateSalary();
int expectedValue=600;
Assert.equals(expectedValue,actualValue);
}
}
Here, even though I have mocked the Appraisal calculator object, it still calls the real appraisal() method from AppraisalCalculator. If the actual AppraisalCalculator at line 1 is created using new Operator instead of newInstance() then this mocking works.
Can anyone explain why this is not working if the actual object is created using reflection? What can I do to mock this Object in such scenario?
Let me first start by rephrasing your question will fully working code.
#RunWith(PowerMockRunner.class)
#PrepareForTest(Employee.class)
public class TestRunner {
#Test
public void test() throws Exception {
AppraisalCalculator acMock = PowerMockito.mock(AppraisalCalculator.class);
PowerMockito
.whenNew(AppraisalCalculator.class)
.withNoArguments()
.thenReturn(acMock);
when(acMock.appraisal()).thenReturn(600);
Employee emp = new Employee();
int actualValue = emp.updateSalary();
int expectedValue = 600;
assertEquals(expectedValue, actualValue);
}
}
Then, the way PowerMock works is that the PowerMockRunner will look at each class that needs to be prepared (here Employee), then look for a call to the constructor we want to replace and do it. This is done at class loading. The real class bytecode calling the constructor is replaced by the one returning the mock.
The thing is that if you are using reflection, PowerMock can't know by reading the bytecode that this constructor will be called. It will only be known dynamically afterwards. So no mocking done.
If you really do need to create the class to be mocked by reflection, I would actually refactor the code a bit.
In Employee I would add something like
protected AppraisalCalculator getCalculator() {
try {
return AppraisalCalculator.class.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
while is a method dedicated to isolate the calculator construction.
The, just create a child class
#Test
public void testWithChildClass() {
// Note that you don't need PowerMock anymore
AppraisalCalculator acMock = Mockito.mock(AppraisalCalculator.class);
when(acMock.appraisal()).thenReturn(600);
Employee emp = new Employee() {
#Override
protected AppraisalCalculator getCalculator() {
return acMock;
}
};
int actualValue = emp.updateSalary();
int expectedValue = 600;
assertEquals(expectedValue, actualValue);
}
or a partial mock (spy)
#Test
public void test2() {
// No PowerMock either here
AppraisalCalculator acMock = Mockito.mock(AppraisalCalculator.class);
when(acMock.appraisal()).thenReturn(600);
Employee emp = spy(new Employee());
doReturn(acMock).when(emp).getCalculator();
int actualValue = emp.updateSalary();
int expectedValue = 600;
assertEquals(expectedValue, actualValue);
}
I often need to use some class which itself have to load some dependency to work.
However, my component can have more than one concrete dependency implementation and it will choose one, rather than another one on some object parameter basis.
The real problem is that the object parameter is always unknown when application start up, so I'm not able in this moment to register any dependency, neither to resolve them.
Instead, for instance, when I need to use some class which itself needs to load some dependency I know the object parameter used by concreteBuilder in order to return me the appropriate implementation:
interface ISample { }
class ParamForBuildSomeISampleImplementation
{
// this instance cannot be create by my startUpApplication - Container - Resolver.
// Instead, all time dependency is required (buttonClick, pageLoad and so on), this class can be instantiated.
}
class Sample1 : ISample
{
// some implementation
}
class Sample2 : ISample
{
// some other implementation
}
class MyISampleFactory
{
// Build ISample
public ISample Build(ParamForBuilderISample obj)
{
// if obj.someProperty == ".." return new Sample1();
// else if obj.someProperty == "--" return new Sample2();
// else if ...
}
}
class NeedsDependency
{
ISample _someSample;
public NeedsDependency(ISample someSample)
{
_someSample = someSample;
}
}
// *** Controllor - ApplicationStartup - other ***
// Here I have not idea how to build ISample dependency
## EDIT
// *** button click event handler ***
// Ok, here I know how to create ParamForBuilderISample,
// hence I can call MyISampleFactory, then, I can Use NeedDependency class:
ParamForBuilderISample obj = new ...
obj.SomeProperty = ...
obj.otherSomeProperty = ...
ISample sample = MyISampleFactory.Build(obj);
NeedDependency nd = new NeedDependency(sample);
// perfect, now my buttonClick can execute all what it wants
nd.DoSomething();
nd.DoOtherStuff();
Is my scenario suitable to Dependency Injection pattern? If true, I really have not idea how build my pattern.
Instead of using constructor injection for passing in this 'runtime dependency', you might be better of using method injection. This might even completely remove the need for having a factory:
private readonly ISample sample;
public MyController(ISample sample) {
this.sample = sample;
}
public string button_click_event_handler(object s, EventArgs e) {
ParamForBuilderISample obj = new ...
obj.SomeProperty = ...
obj.otherSomeProperty = ...
this.sample.DoSomething(obj);
}
You still need to switch somewhere, but instead of having a factory, you could implement a proxy for ISample:
public class SampleProxy : ISample
{
private readonly Sample1 sample1;
private readonly Sample2 sample2;
public SampleProxy(Sample1 sample1, Sample2 sample2) {
this.sample1 = sample1;
this.sample2 = sample2;
}
public void DoSomething(ParamForBuilderISample param) {
this.GetSampleFor(param).DoSomething(param);
}
private ISample GetSampleFor(ParamForBuilderISample param) {
// if obj.someProperty == ".." return this.sample1;
// else if obj.someProperty == "--" return this.sample2;
// else if ...
}
}
Your ParamForBuilderISample looks like a parameter object. Dependency injection doesn't remove the need to have method arguments. Data should still be passed on through methods.
I am relatively new to C#, maybe you could help me with this.
I got a couple of methods callServiceXY(param1, param2, ...) that call a certain service. For many reasons these service calls can go wrong (and I don't really care for the reason in the end). So basically I need to always wrap them with something like this - to have them execute again if something goes wrong:
var i = 3;
while(i>0)
try{
call...()
} catch{
i--;
}
i=0;
}
I'd rather write this code only once. Could I somehow have a method like tryXtimes(int x, callService()) that allows me to execute an undefined or anonymous method? (I have Javascript in mind where this is possible...)?
Yes this is possible. C# 3.5 added support for Action and Func<T> types. An Action won't return any value, a Func will always return a value.
You have several different versions that also accept a number of parameters. The following Console Applications describes how you could do this:
using System;
namespace Stackoverflow
{
class Service
{
public int MyMethod() { return 42; }
public void MyMethod(string param1, bool param2) { }
public int MyMethod(object paramY) { return 42; }
}
class Program
{
static void ExecuteWithRetry(Action action)
{
try
{
action();
}
catch
{
action();
}
}
static T ExecuteWithRetry<T>(Func<T> function)
{
try
{
return function();
}
catch
{
return function();
}
}
static void Main(string[] args)
{
Service s = new Service();
ExecuteWithRetry(() => s.MyMethod("a", true));
int a = ExecuteWithRetry(() => s.MyMethod(1));
int b = ExecuteWithRetry(() => s.MyMethod(true));
}
}
}
As you can see, there are two overloads for ExecuteWithRetry. One returning void, one returning a type. You can call ExecuteWithRetry by passing an Action or a Func.
--> Edit: Awesome! Just a little extra code to complete the example:
With anonymous function/method:
ExecuteWithRetry(() =>
{
logger.Debug("test");
});
And with more parameters (action, int)
Method header:
public static void ExecuteWithRetryX(Action a, int x)
Method call:
ExecuteWithRetryX(() => { logger.Debug("test"); }, 2);
I would use the strategy/factory pattern(s) for this. This answer https://stackoverflow.com/a/13641801/626442 gives and example of the use of the strategy/factory pattern with links. The question at the above link will give you another type of example where this pattern can be adopted.
There are great examples of these design patterns here and the following are detailed intros to the Strategy pattern and the Factory pattern. The former of the last two links also shows you how to combine the two to do something like what you require.
I hope this helps.
Try following
void CallServiceXY(params object []objects)
{
Console.WriteLine("a");
throw new Exception("");
}
void Retry(int maxRetryCount, Action<object[]> action, params object[] obj)
{
int retryCount = 1;
while ( retryCount <= maxRetryCount)
{
try
{
action(obj);
return;
}
catch
{
retryCount++;
}
}
}
void Main()
{
Retry(2,CallServiceXY);
Retry(2,CallServiceXY,"");
Retry(2,CallServiceXY,"","");
}
Demo here
Trick is Action<object[]> that accepts object array and return void and params keyword in Retry method.
To return non void value, Change Action<object[]> to Func<T, object[]>.
I have a state machine that needs to call a different method on each object from a List of objects depending on the state I'm in. Basically I'm trying to refactor the code that has a loop in each case statement of my state machine so that it looks like the code below. However I cannot seem to figure out how to pass the relevant method to my refactored function (not to mention I then don't know how to call it on each item)
Any help would be appreciated.
Here's the example code:
public class MyOtherType
{
public bool Method1()
{ return false; }
public bool Method2()
{ return false; }
public bool Method3()
{ return false; }
public bool Method4()
{ return false; }
}
public class MyType
{
public enum MyState
{
DoSomething1,
DoSomething2,
DoSomething3,
DoSomething4
}
private MyState State = MyState.DoSomething1;
List<MyOtherType> MyListOfObjects = new List<MyOtherType>() { new MyOtherType(), new MyOtherType() };
private void StateMachine()
{
switch (State)
{
case MyState.DoSomething1:
//How do I pass this in? Do I need to set it up differnetly?
Process(() => MyOtherType.Method1());
break;
case MyState.DoSomething2:
Process(() => MyOtherType.Method2);
break;
case MyState.DoSomething3:
Process(() => MyOtherType.Method3);
break;
case MyState.DoSomething4:
Process(() => MyOtherType.Method4);
break;
}
}
private void Process(Func<bool> method)
{
foreach (MyOtherType item in MyListOfObjects)
{
//How do I call the method on each item?
if (item.method())
{
//Do something
}
}
}
}
I would suggest to get rid of such switch blocks and decouple each specific method from a state by introducing flexible map of strategy per state so it could be easily changed or even injected:
IDictionary<MyState, Func<bool>> strategyMap;
1) Fill it in
// if idea is to access methods without instance of MyOtherType -
// make all methods and class itself static so you can access it
// like MyOtherType.Method1
strategyMap = new Dictionary<MyState, Func<bool>>();
strategyMap.Add(MyState.DoSomething1, myOtherTypeInstance.Method1);
2) Call appropriate strategy depends on state instead of switch(State)
if (starategyMap.ContainsKey(State))
{
// pass in an associated strategy
Process(starategyMap[State]);
}
Feel free to ask in case of any questions
One possible solution is to make the methods static and take the class reference they shall operate on as a parameter:
public class MyOtherType
{
public static bool Method1(MyOtherType instance)
{
return instance == null;
}
}