infinite / mockito-flex

0 stars 0 forks source link

Cannot mock a function #19

Open infinite opened 10 years ago

infinite commented 10 years ago

Given the following class: {{{

!actionscript

public class SomeClass { public function SomeClass() {}

 public var broadcastFunction:Function;

}

// Associated test class: public class SomeClassTest { [Mock] public var mockClass:SomeClass;

 [Test]
 public function test():void {
     mockClass.broadcastFunction();
     verify().that(mockClass.broadcastFunction());
}

} }}}

The above fails citing "value is not a function".

We use the above functionality as part of Parsley, where the the broadcastFunction would be annotated as a [MessageDispatcher].

Being able to mock this would mean we can test classes ensuring that they have broadcast messages as expected.

Regards

Marty

infinite commented 10 years ago

From loomis on 2010-04-26 18:32:16+00:00

Thanks for submitting this yet this is not a real defect.

Here is what happens:

If you look at the signature, the broadcastFunction is not really a function but a public field. Mockito is unable to mock such a thing. Even if you change it into a property by making appropriate get/set function, still Mockito will be able only to detect read or write access to the property not the actual invocation of a function. What you can do though to ensure this function gets called is to create some helper class with a some function, mock it and assign this function to the broadcastFunction field. Then you would verify calling the helper function instead of the actual broadcastFunction reference.

{{{

!as3

public HelperClass { public function helperBroadcastFunction():void { } }

public class SomeClass { public function SomeClass() {}

 public var broadcastFunction:Function;

}

// Associated test class: public class SomeClassTest { [Mock] public var helperClass:HelperClass;

 public var mockClass:SomeClass;

 [Test]
 public function test():void {
     // given
     someClass.broadcastFunction = helperClass.helperBroadcastFunction;
     // when
     mockClass.broadcastFunction();
     // then
     verify().that(helperClass.helperBroadcastFunction());
}

}

}}}

Let me know if you got it to work.

Cheers, Kris