OCMock testing the address of a struct - objective-c

I have some code I want to test that is passing around the address of a struct:
MyObject myObject = ...;
MyRecord record = [someObject record]; //record is a #property
[myObject add:&record];
I've mocked someObject to return a record:
MyRecord record = ...;
[[[_mockSomeObject stub] andReturnValue:OCMOCK_VALUE(record)] record];
[[_mockMyObject expect] add:&record];
Unfortunately, OCMock fails (I believe) because pulling the struct out of the NSValue wrapper will always return a different address.
Is there a way to get an expectation to work correctly if one of the parameters is an address of a struct?

Look at this post on returning structs with OCMock. Looks like the OCMOCK_VALUE macro just won't cut it.

Related

Bulding property paths programatically with another class's selectors. How does this work?

I have a method I that takes a variable number of #selector() values and returns a proper NSString I found on this site a while back. This is useful when building property paths for me because I don't like the idea of using strings for this and like the idea of the compiler being able to check the values the path is built from. The method is:
+(NSString *)keyPathFromSelectors:(SEL)firstArg, ...
{
NSMutableArray *keys = [NSMutableArray array];
va_list args;
va_start(args, firstArg);
for (SEL arg = firstArg; arg != nil; arg = va_arg(args, SEL))
{
[keys addObject:NSStringFromSelector(arg)];
}
va_end(args);
return [keys componentsJoinedByString:#"."];
}
This works beautifully but the question is: Why? If I have property on my current object named person and it has a name the path would be person.name obviously and the call to my method would look like:
+(NSSet *)keyPathsForValuesAffectingFoo
{
return [NSSet setWithObject:[self keyPathFromSelectors:#selector(person), #selector(name),nil]];
}
The name selector is (should not) technically visible in my current class, it's in the Person class to which I have a reference so how am I accessing the correct name SEL object?
Selectors are do not carry the guarantee that the method actually exists on the object in question. You can get compiler warnings that a selector name doesn't exist anywhere, but you won't get assurance that it does exist on the object it will be used on. For example, this compiles:
[person performSelector: #selector(applicationDidBecomeActive:)]
Even though applicationDidBecomeActive exists on your app delegate and not person.
However! This kind of thing is possible through compiler macros. Look at the libextobjc library which provides exactly the kind of selector/key path compile time checking you're looking for. This is what powers a lot of the keypath magic in ReactiveCocoa but it can also be used standalone.

Objective-c Code Blocks as nested method

Is it possible to have an nested method in Obj-c. What I an trying to do is create a specific object when initialising an NSArray:
NSArray array = #[
^{ NSViewController someObject = ...
someObject.someObjectProperty = #"Bla";
return someObject},
^{ NSViewController someOtherObject = ...
someOtherObject.someOtherObjectProperty = #"Bla Bla";
return someObject},
];
The array contains __NSGlobalBlock__, where I am trying to get [someObject, someOtherObject]
The array is returning a stack of ViewControllers and I need to set different properties on each of them.
Thanks
Code blocks are not just "for execution sometime in the future". They can be used that way, but they can certainly be used in the way you suggest; they are a lambda. Of course, you have the syntax all wrong, because you are describing the block, not calling it. (Though an array containing blocks is also perfectly reasonable.)
If I understand you correctly, you want to create a local block and add its return value directly to the array. While it's not a mainstream method, it is possible:
NSArray *array = #[
(id)^{
id someObject = ...
someObject.aProp = #"Bla";
return someObject;
}(), // here you immediately execute the local block
(id)^{
id someObject = ...
someObject.aProp = #"Bla";
return someObject;
}()
];

Getting the class type for a nil object?

If I have an object that is already allocated, then doing object.class returns a non-nil value. So far so good. But, if the object has not yet been allocated, then accessing object.class returns nil.
I want to allocate an object based on its type dynamically, so for example:
#property NSArray *myArray;
...
// myArray is nil so far
self.myArray = [_myArray.class new];
However, I can't do this because _myArray.class is returning nil. So how would I determine the class type of a nil instance?
Update:
It is in fact possible. Check out my answer below.
You cannot determine the class of a nil instance, because it does not have one: it can be, quite literally, of any type derived from the type of the variable. For example, NSMutableArray is perfectly compatible with NSArray:
NSArray *myArray = [NSArray new]; // OK
NSArray *myArray = [NSMutableArray new]; // Also OK
Since the run-time capabilities of different subclasses can vary a lot, it is always up to your program to decide what kind of objects it wants.
Objective-C is a duck-typed language. This means that there are several things you can or can't do, and one of the things you can't is statically get a reference to the type of a variable.
Specifically, in your expression:
[_myArray.class new]
First, _myArray.class is evaluated, and then the result is sent the new message. Since _myArray is nil to begin with, _myArray.class returns nil as well, and the new message will return nil too, because sending any message to nil returns nil (or the closest representation to zero the return type has). This is why it doesn't work.
I suspect you come from a strongly-typed language like C#; what you're doing right now is the equivalent of Foo foo = (Foo)Activator.CreateInstance(foo.GetType()), which is sure to fail because foo.GetType() will either not compile or throw an exception (depending on if it's a class field or a local variable) since it was never assigned a value. In Objective-C, it compiles but it doesn't works. What you would want is Activator.CreateInstance(typeof(Foo)), but notice that Foo is now hardcoded here too, so you might as well just create a new Foo().
You say that the compiler "knows the type" of the object. This is not exactly true. First, NSArray and NSMutableArray are the root classes of the NSArray class cluster. This means that both are abstract, and [NSArray alloc] and [NSMutableArray alloc] return an instance of a subclass (NSCFArray last time I checked, and possibly something else; I recall seeing _NSArrayM). Maybe [NSArray new] works, but it's not giving you a plain NSArray.
Second, type safety is not enforced. Consider this code:
id foo = #"foo";
NSArray* bar = foo; // no warning!
So even though the compiler thinks that bar is an NSArray, it's in fact a NSString. If we plug in your code:
id foo = #"foo";
NSArray* bar = foo; // no warning!
NSArray* baz = [bar.class new];
baz is now an NSString as well. Since you ask for the runtime class of bar, the compiler has nothing to do with the operations.
And precisely because of that kind of behavior, you should probably instantiate your object with a class that you know, using [NSArray new] instead of trusting _myArray to be non-nil, and to be what you think it is.
You must init the property , or it will be nil , send a message to a nil object , it will return nil , so ,you must first init the array like _array = [[NSArray alloc] init];
So, for anyone wondering if this is possible, it is:
objc_property_t property = class_getProperty(self.class, "myArray");
const char * const attrString = property_getAttributes(property);
const char *typeString = attrString + 1;
const char *next = NSGetSizeAndAlignment(typeString, NULL, NULL);
const char *className = typeString + 2;
next = strchr(className, '"');
size_t classNameLength = next - className;
char trimmedName[classNameLength + 1];
strncpy(trimmedName, className, classNameLength);
trimmedName[classNameLength] = '\0';
Class objectClass = objc_getClass(trimmedName);
NSLog(#"%#", objectClass);
Output:
NSArray
Done with the help of extobjc.
Nil has no class type
In Objective-C the actual class on an instance variable is only determined at runtime. So, you can't know the class of a nil object.
This is not an issue in your situation since you only need to do:
NSArray *myArray = [NSArray new];
Or
NSArray *myArray = [[NSArray alloc] init];
In Objective-C most decisions are deferred to the runtime
(as much as possible)
Objective-C is a runtime oriented language, which means that when it's
possible it defers decisions about what will actually be executed from
compile & link time to when it's actually executing on the runtime.
This gives you a lot of flexibility in that you can redirect messages
to appropriate objects as you need to or you can even intentionally
swap method implementations, etc.
This requires the use of a runtime
which can introspect objects to see what they do & don't respond to
and dispatch methods appropriately. If we contrast this to a language
like C. In C you start out with a main() method and then from there
it's pretty much a top down design of following your logic and
executing functions as you've written your code. A C struct can't
forward requests to perform a function onto other targets.
Source: Understanding the Objective-C Runtime

How to set expectations on parameters to mocked methods in Kiwi

Using OCMockito and OCHamcrest, I can set up expectations on the arguments to mocked methods, thusly:
[verify(aMockObject) doSomething:allOf(is(instanceOf([NSArray class])), hasCountOf(3U), nil)];
There doesn't seem to be an equivalently simple way to do this using Kiwi. It is possible to capture arguments using a spy, something like:
KWCaptureSpy *spy = [aMockObject captureArgument:#selector(doSomething:) atIndex:0];
NSArray *capturedArray = spy.argument;
And then to check expectations on the captured object:
[[capturedArray should] haveCountOf:3U];
Is there a less clumsy way to do this in Kiwi?
(I'm aware I could probably use hamcrest matchers in here, but for the moment I'm exploring what Kiwi is capable of).
One option that I have used is stub:withBlock:
NSArray* capturedArray; // declare this as __block if needed
[aMockObject stub:#selector(doSomething:)
withBlock:^id(NSArray *params) {
capturedArray = params[0];
// this is necessary even if the doSomething method returns void
return nil;
}];
// exercise your object under test, then:
[[capturedArray should] haveCountOf:3U];
This works fine, and I find it easier to implement than the spy pattern. But your question made me wonder about expectations using message patterns. For example:
[[[aMockObject should] receive] doSomething:myArray];
[[[aMockObject should] receive] doSomething:any()];
The first example will verify that aMockObject received the doSomething: message with an argument that isEqual:myArray. The second example will simply verify that doSomething: was sent, with no expectation about the array arugment. It would be great if we can specify some type of Matcher in the message pattern, to express that we don't care what specific array instance is sent in the message, just that it has a count of 3.
I haven't found any examples of being able to do this, but it looks like there are some possibilities. To verify a message-sending expectation, Kiwi uses the KWMessagePattern class, specifically the matchesInvocation: and argumentFiltersMatchInvocationArguments: methods. This checks for three types of "argument filters":
Literal object values (such as myArray in the example above), which are compared to the actual value sent in the message using isEqual:
An object of type KWAny (such as the any() macro in the example above), which will match any argument value
Objects that satisfy [KWGenericMatchEvaluator isGenericMatcher:argumentFilter], which basically means that the object responds to matches:(id)obj
Thus, you should be able to use objects that implement matches: in message-pattern expectations to do things like verify the length of arrays sent to stubbed methods, without resorting to spys or blocks. Here's a very simple implementation: (available as a Gist)
// A reusable class that satisfies isGenericMatcher:
#interface SOHaveCountOfGenericMatcher : NSObject
- (id)initWithCount:(NSUInteger)count;
- (BOOL)matches:(id)item; // this is what KWMessagePattern looks for
#property (readonly, nonatomic) NSUInteger count;
#end
#implementation SOHaveCountOfGenericMatcher
- (id)initWithCount:(NSUInteger)count
{
if (self = [super init]) {
_count = count;
}
return self;
}
- (BOOL)matches:(id)item
{
if (![item respondsToSelector:#selector(count)])
return NO;
return [item count] == self.count;
}
#end
// Your spec:
it(#"should receive an array with count 3", ^{
NSArray* testArray = #[#"a", #"b", #"c"];
id argWithCount3 = [[SOHaveCountOfGenericMatcher alloc] initWithCount:3];
id aMockObject = [SomeObj nullMock];
[[[aMockObject should] receive] doSomething:argWithCount3];
[aMockObject doSomething:testArray];
});
It would be nice to be able to reuse Kiwi's built-in matcher classes here, but I haven't yet found out exactly how to do this.

How do I pass arrays of values to SudzC-generated webservice classes?

I have a sudzc service class generated from a WSDL that accepts an ArrayOfInt and ArrayOfString objects as parameters. The service method signature is this:
- (SoapRequest*) Search: (id <SoapDelegate>) handler filters: (NSMutableArray*) displayedAttributes: (NSMutableArray*) displayedAttributes;
My question is, how do I pass values into the parameters that expect NSMutableArrays?
In the above method signature, the "displayedAttributes" parameter is expecting an ArrayOfInt object (which should be populated with several integers in an int tag, e.g., <int>1</int><int>2</int><int>3</int> etc).
However none of these things which I've tried have worked:
Directly passing an NSArray/NSMutableArray of (int) objects
Directly passing an NSArray/NSMutableArray of NSNumber objects
Passing an array of strings containing #"1", #"2", #"3" etc
Passing an array of strings that already contain #"<int>1</int>", #"<int>2</int>", etc
Constructing a CXMLDocument out of a string based on the integers
I'm sure this is somehow explained in the accompanying documentation in the download -- it's just not clear to me at the moment.
#Jon Limjap: Lucky you are!!! it asks you for a type which you have dealt before, I have custom class type that SudzC generated for me (!)... It initializes only when passed CXMLNode, (which need CXMLDocument / CXMLElement).. I have no idea how to deal with such type...
an instance is: filter is a class, I have a class of the filter, but there is no way to initialize it, (except alloc-init and then setting its properties, but its properties are another such custom type.. !!!!)...If you know any "trick" to tell/configure sudzc to allow us to pass objects or fetch objects of cocoa type, do tell me....
I had similar situation of passing array of objects to SOAP request. I managed to get it working by doing following changes.
SOAP array case in not added in
+(NSString *) serialize: (id) object()
{
//look if it is array not implemented
}
so I managed to change in the following method
+ (NSString*) serialize: (id) object withName: (NSString*) nodeName {
if([object respondsToSelector:#selector(serialize:)]) {
if([object isKindOfClass:[SoapArray class]])
return [object serialize:object];
return [object serialize: nodeName];
}
NSString *temp =[NSString stringWithFormat:#"<%#>%#</%#>", nodeName, [Soap serialize: object], nodeName];
NSLog(#"serialise = %#", temp);
return temp;
}
at the time SOAP request,
NSMutableArray arr = [[MYTable_STUB_ARR alloc] init]
MYTABLE_OBJ *obj = [[MYTABLE_OBJ alloc] init];
[arr addObject:obj];
[obj release];
Pass element arr object your SOAP Request ??
This is a bit old, but I hope it will help someone. I implemented the serialize: method on SoapArray this way:
- (NSMutableString *)serialize:(NSString *)name
{
NSMutableString *str = [NSMutableString string];
//[str appendFormat:#"<%#>", name];
for (id content in self)
{
//[str appendString:[Soap serialize:content]];
[str appendString:[Soap serialize:content withName:name]];
}
//[str appendFormat:#"</%#>", name];
return str;
}
As you can see, there are some commented lines. If you uncomment them and comment the currently used one inside the for, you will get a tag named name which will contain objects tagged with the content class name.