OCMock 3 Partial Mock: Class methods and the objc runtime - ocmock

I'm running into an interesting issue when using OCMock 3 when partially mocking an object that defines class methods. I'm not sure if this is an issue with the dynamic subclassing that takes part as partial mocking or my misunderstanding of the objc runtime. Any help would be greatly appreciated.
As part of running tests and other debug builds we do some runtime verification of method declarations using OmniFoundations' OBRuntimeCheck. One of these checks, in short, attempts to use the runtime to verify that type signatures match for class methods across inheritance and protocol conformance. This happens by listing the classes registered in the runtime and for each class the instance methods of the metaClass are copied. For each Method from the metaClass if it exists on the metaClass's superclass the type signatures are compared.
The problem comes when calling class_getInstanceMethod on the metaClass's superclass for one of the ocmock replacement selectors, ocmock_replaced_*. The test crashes EXC_BAD_INSTRUCTION code=EXC_i386_INVOP subcode=0x0 and no class for metaclass is logged in the console. Example given:
class_getInstanceMethod(metaSuperClass, NSSelectorFromString(#"ocmock_replaced_classMessage"))
When partial mocking an object that defines a class method, it appears that the OCMock 3 framework generates a dynamic subclass, does some isa swizzling of the mocked object and also some isa swizzling of the dynamically generated class' metaClass.
This behavior and crash is new in OCMock 3 and I'm really at a loss of where to look next. Any runtime gurus have any idea what may be going on here? When looking through the code it did surprise me that the dynamically generated class used for the mock was having it's meta class swizzled out, but I don't necessarily think that is wrong. For ease in debugging I have created a simplified test case in a fresh fork of OCMock. The crashing test can be found here. Any help for guidance would be greatly appreciated.

I may be way off here, but I thought the superclass of a metaClass is NSObject (which is why you can normally call NSObject instance methods on class objects). I'm not sure you should be doing anything, normally, with the superclass of a metaClass.
In general, the metaClass stores all of the information about class methods. Therefore, getting an "instance" method on a metaClass is the same as getting a class method on the associated regular Class. The runtime can simply dereference the "isa" pointer of an instance to find a method list to find instance methods; doing the same on a Class object gets the meta class (of the same structure) and therefore the same process results in finding the class methods.
OCMock will create a magic subclass for any partial mock, and change the class on that instance to the new subclass, so all the instance method swizzling will be specific to that instance. For class methods though, I thought it had to modify the original class itself -- otherwise, calls to the regular class method in regular code would not be intercepted. It keeps a copy of the original implementation so that when you call -stopMocking on the mock it can restore the original implementation (the added ocmock_replaced* impl will still be there but should no longer be called).
You could simply ignore any selector which starts with "ocmock_replaced" since that really is not related to your actual code you are presumably checking. You might also have better luck changing "class_getInstanceMethod(metaSuperClass, ..." to "class_getClassMethod(regularSuperClass, ..."). I'm not sure why you would be getting a crash though -- I would expect class_getInstanceMethod(metaSuperClass, ...) to just return NULL in most situations.

Related

PHPUnit Mock Object replacing Real Class

I have a couple of tests in my test suite being run in Zend_Test
One test creates a mock of Foo_Bar_Baz via PHPUnit's MockBuilder as that class its dependency. Now in the test for Foo_BAR_baz (the change in case is on purpose and is necessary due to autoloading), I am not getting the class but rather an instance of the mock, which obviously doesn't work.
Doing a var_dump on the object results in class Foo_Bar_Baz#27115(0) { } so it appears to be creating an instance of the mock.
Fixing the case of in the mock gets things to work as expected. I have never seen this behavior in mocking objects before. For some reason the mocked class is being loaded into PHP so that when the next test tries to instantiate the real object it instantiates the mock instead. Why would this be happening?
Class names in PHP are not case-sensitive, but filenames on a *nix server are.
I suspect the change in case is causing a change in behaviour because of an autoload mechanism; PHP would only autoload one of Foo_Bar_Baz.php and Foo_BAR_Baz.php.
In your case, if you have already defined a class Foo_BAR_Baz (as a mock) then PHP will use the same definition for Foo_Bar_Baz, thereby ignoring your real class definition.

overriding a constructor

This is a simple questions. I have researched this questions in my notebooks and books and the internet but cant find an answer
Why would we override the default constructor by adding parameters to it?
You would create a constructor for a class to manipulate its member variables according to whatever other conditions as soon as it's created. I get the impression you don't actually know what a constructor is.
Many languages (like C++/C#/Java) automatically create default no-arguments constructor when none defined in the class explicitly.
When you create a constructor in a class with or without arguments usually compiler stop creating default auto-generated constructor (depending on language specification). This is done on assumption if you have some non default initialization than automatically generated one is likely to not create object in a state you would expect.
Since having constructor with arguments is natural way to create objects it is essentially lead to "removing" default auto-generated constructor which probably can be called "overriding default constructor".

Should I use a singleton class that inherits from an instantiable class or there's another better pattern?

I've got a class called ArtificialIntelligenceBase from which you can create your own artificial intelligence configuration sending some variables to the constructor or you can make a class that inherits from ArtificialIntelligenceBase and in the constructor of this new class just call the function super() with the parameters of the configurations.
I've also created some examples of artificial intelligences in classes, AIPassive, AIAgressive and AIDefensive. Obviously all of them inherits from ArtificialIntelligenceBase.
The point is that there're only few public functions in the base class. The variables in the base class are read only and the non public functions are protected in case you need to apply some modifications on them when created another pre-defined AI.
You can also create another AI just calling the base class sending some parameters in the constructor like this: new ArtificialIntelligenceBase(param1, param2, param3, param4);
I've tought about make the classes as a singleton because the classes can never change and once setted, their variables never change.
The question is: Is the singleton the best pattern to do this? Because I'm not sure.
PD: You don't need to explain any patter, just mention the name and I'll search for how it works
PPD: I'm developing in AS3. Just in case it helps
Thanks
In general, singletons are evil. I don't see any reason in your case to use a singleton, either. It sounds like you're using your own version of a factory method pattern (using a constructor somehow?) or maybe a prototype (I don't know AS3 one bit), but if you're looking for other patterns a couple of other ones are abstract factory and builder.
You don't need to use the singleton pattern to limit yourself to using only one instance per type of class, though. It doesn't help avoid redundancy.

Calling a getter without assigning it to anything (lazy loading)

I have a DTO which can be fully loaded or lazy loaded using Lazy Load Pattern. How it is loaded depends on what the Flex Application needs. However, this DTO will be sent to a Flex application (swf). Normally, a collection for instance, will only be loaded when called. In my case however, the collection will only be called in Flex, so my implementation on the .NET side will obviously not work in this case (except if Flex would do a server call... something I would like to avoid).
In the getter of the collection, the data is retrieved from the database. If I would be working with ASP.NET pages, it would work, but not if the DTO is sent to Flex.
How would you deal with this? I could call the getter before sending the DTO to Flex, but that seems awful... + calling the getter can only be done if it is assigned to something (and the local variable that will hold the collection will never be used...).
You can introduce a method to load dependents - loadDependencies - that should take of all lazy loading for your DTO object before being sent over the wire (to Flex). You can abstract this method to an interface to streamline such process across different DTOs. There is nothing against using getters the way you described it inside this method.
I would probably introduce a Finalize method for the class and perhaps a FinalizeAll extension method for various collections of the class. This method would simply go through and reference all the getters on the public properties of the class to ensure that they are loaded. You would invoke Finalize (or FinalizeAll) before sending the object(s) to your Flex app. You might even want to make this an interface so that you can test for the need for finalization before transfering your objects and invoke the method based on a test for the interface rather than checking for each class individually.
NOTE: Finalize is just the first name that popped into mind. There may be (probably is) a better name for this.

Why is object returned from getDefinitionByName()?

In Actionscript 3, why does getDefinitionByName() return an Object when the docs say:
Returns a reference to the class object of the class specified by the name parameter.
Based on that, I would conclude that the returned object should be Class instead of Object. Can someone enlighten me why that is not the case?
getDefinitionByName can also return a Function, such as getDefinitionByName('flash.utils.getDefinitionByName').
This only works on namespace-level functions, though, not static class methods.
Despite the method signature, getDefinitionByName does return Class. I think the misleading signature is due to the method existing before the Class object (when it used to return an anonymous/extended object instance).
Perhaps Adobe considered that this function might return different values in a future version of Flash Player. For instance, ECMAScript, the standard on which ActionScript is based, has historically used Function objects with prototypes as the basis for class-like objects. During discussions of the newest versions of the ECMAScript standard, there has been sugestions for "freezing" function-based classes at run-time to make them into something like compile-time Class objects. What if you could also specify a definition name for them? Are they actually of type Class at this point, or are they still or type Function? Probably the later, in my opinion. Both 'Class' and 'Function' references can be generalized as Object, so that return type makes sense in this context.
Note: This explanation is purely speculation based on what I've read in the ECMAScript specification wiki and the blogs of various committee members.

Resources