Unit test a very simple method, but failed - ios

I have a simple School class which defines a init method:
#implementation School
- (id) init {
self = [super init];
if (self) {
// call class method of MyHelper class
if ([MyHelper isWeekend]) {
[MyHelper doSomething];
}
}
}
#end
(MyHelper is a class contains only class methods, the isWeekend is a class method returns a boolean value)
I use OCMock to unit test this simple init method:
- (void)testInit {
// mock a school instance
id schoolMock = [OCMockObject partialMockForObject:[[School alloc] init]];
// mock class MyHelper
id MyHelperMock = OCMStrictClassMock([MyHelper class]);
// stub class method 'isWeekend()' to return true
OCMExpect([MyHelperMock isWeekend]).andReturn(true);
// run init method
[schoolMock init];
// verify
OCMVerify([MyHelperMock isWeekend]);
}
But when run it, I get error:
OCMockObject(MyHelper): Method isWeekend was not invoked. why?

You've created a mock for the MyHelper class, but this isn't going to be used within the implementation of your School object. You'd only get the mocked response if you wrote [MyHelperMock isWeekend], which you can't do inside the initialiser without rewriting it for tests.
To make your School class more testable you should be passing in any dependencies on initialisation. For example, you could pass in the isWeekend value as part of the initialiser, instead of obtaining it inside the method, or pass in the class object (MyHelper or MyHelperMock).
It's worth noting that finding certain classes or methods difficult to test because of things like this is often a good indicator that your code isn't structured very well.

Related

What's the internal structure of self?

Why can self be used in implementation methods, or in class methods? What's the internal structure of self? eg:
#import "Person.h"
#implementation Person
+ (void)initialize
{
[super initialize];
[self setupModel];
}
- (instancetype)init
{
self = [super init];
if (self) {
[self test];
}
return self;
}
+ (void)setupModel
{
NSLog(#"setup a person object");
}
- (void)test
{
NSLog(#"this method is called");
}
#end
Code run results:
2018-09-17 09:32:40.615578+0800 Test[662:301213] setup a person object
2018-09-17 09:32:40.615662+0800 Test[662:301213] this method is called
Code run results
For instance methods, self is a reference to the current object.
For class methods, self is a reference to the current class.
If you declare an Objective-C method like this
- (void)doSomethingWithObject:(id)object { ... }
the compiler basically just turns it into a a C function with the following signature:
void _i_classname_doSomethingWithObject_(const id self, const SEL _cmd, id object) { ... }
(where classname is the name of the class the method belongs to. for class methods, the i becomes a c)
When you call the method [foo doSomethingWithObject:bar], the compiler turns that method call into a call to objc_msgSend, which "forwards" the call to the correct implementation:
objc_msgSend(foo, #selector(doSomethingWithObject:), bar);
As you can see, the parameters passed to objc_megSend are the same expected by the C function containing the implementation of the Objective-C method.
These are implementation details, so you shouldn't rely on them:
self is either a tagged pointer or a genuine pointer to an struct that starts with the isa field and then contains all of the object's instance variables.
The isa field is itself either a set of bitfields that contains the instance's retain contain, some flags, and a pointer to the Class of the instance, or (on older and 32-bit platforms) it is just a pointer to the Class of the instance (in which case the retain count is stored in a global hash table).

Use of undeclared identifier error in my case

My code invokes a C library function:
#implementation Store
...
-(void) doWork {
// this is a C function from a library
int data = getData();
...
}
end
I am unit testing the above function, I want to mock the C function getData() in my test, here is my test case:
#interface StoreTests : XCTestCase {
int mData;
Store *store;
}
#end
#implementation StoreTests
-(void) setUp {
[super setUp];
mData = 0;
store = [[Store alloc] init];
}
-(void) testDoWork {
// this call will use the mocked getData(), no problem here.
[store doWork];
}
// mocked getData()
int getData() {
mData = 10; // Use of undeclared identifier 'mData', why?
return mData;
}
...
#end
Why I get complier error:
Use of undeclared identifier 'mData' inside mocked getData() function?
You are misunderstanding how instance methods and variables work.
Every instance method has a variable self which references the current instance (or "current object") and a use of an instance variable, such as mData, is shorthand for accessing that variable using self, e.g self->mData, where -> is the (Objective-)C operator for field access. So your setup method written "long hand" is:
-(void) setUp {
[super setUp];
self->mData = 0;
self->store = [[Store alloc] init];
}
But where does self, the reference to the instance, itself come from? Well it's not magical, just hidden, it is passed to an instance method automatically as a hidden extra argument. At this point which switch to pseudo-code to show this. Your setup method is effectively compiled as:
-(void) setUp withSelf:(StoreTest *)self {
[super setUp];
self->mData = 0;
self->store = [[Store alloc] init];
}
and a call such as:
StoreTests *myStoreTests = ...
[myStoreTests setup];
is effectively compiled as something like:
[myStoreTests setup withSelf:myStoreTests];
automatically adding the extra self argument.
Now all the above only applies to methods, and enables them to access instance variables and methods, it does not apply to plain C functions - they have no hidden self argument and cannot access instance variables.
The solution you mention in the answer you added of declaring mData outside of the interface:
int mData;
#interface StoreTests : XCTestCase {
Store *store;
}
#end
changes mData into a global variable, instead of being an instance variable. C functions can access global variables. However this does mean that every instance of the class shares the same mData, there is only one mData in this case rather than one for every instance.
Making an instance variable into a global is therefore not a general solution to to issues like this, however as it is unlikely that you will have more than one instance of your StoreTests class it is a suitable solution in this case.
You should however make one change: you can only have one global variable with a given name with a program, so your mData must be unique and is accessible by any code within your program, not just the code of StoreTests. You can mitigate this my declaring the variable as static:
static int mData;
this keeps the variable as global but only makes it visible to code within the same file as the declaration, which is probably just the code of StoreTests.
HTH
I found one solution for my question, that is declare mData above #interface StoreTests : XCTestCase, something like this:
int mData;
#interface StoreTests : XCTestCase {
Store *store;
}
#end
...

stub function is not working in my test case [duplicate]

This question already has an answer here:
How to mock an object with OCMock which isn't passed as a parameter to method?
(1 answer)
Closed 6 years ago.
I am using OCMock 3 to write my unite tests in iOS project.
I have a foo method under School class:
#implementation School
-(NSString *)foo:
{
// I need to mock this MyService instance in my test
MyService *service = [[MyService alloc] init];
// I need to stub the function return for [service getStudent]
Student *student = [service getStudent];
if (student.age == 12) {
//log the age is 12
} else {
//log the age is not 12
}
...
}
The Student looks like this:
#interface Student : NSObject
#property NSInteger age;
...
#end
In my test case, I want to stub the method call [service getStudent] to return a Student instance with age value 12 I defined:
// use mocked service
id mockService = OCMClassMock([MyService class]);
OCMStub([[mockService alloc] init]).andReturn(mockService);
// create a student instance (with age=12) which I want to return by function '-(Student*) getStudent:'
Student *myStudent = [[Student alloc] init];
myStudent.age = 12;
// stub function to return 'myStudent'
OCMStub([mockService getStudent]).andReturn(myStudent);
// execute foo method
id schoolToTest = [OCMockObject partialMockForObject:[[School alloc] init]];
[schoolToTest foo];
When I run my test case, however, the student returned by -(Student*)getStudent: method is not with age 12, why?
===== UPDATE ====
I noticed in internet, somebody suggested to separate the alloc and init to stub. I also tried it but it doesn't work as it says:
// use mocked service
id mockService = OCMClassMock([MyService class]);
OCMStub([mockService alloc]).andReturn(mockService);
OCMStub([mockService init]).andReturn(mockService);
// stub function to return 'myStudent'
OCMStub([mockService getStudent]).andReturn(myStudent);
When I do this & run my test case, the real implementation of -(Student*)getStudent: method get called... I can't understand why people says it works.
You cannot mock the init method. This is stated in the documentation (Section 9.3), but maybe it's too hidden.

Call method hierarchy in Objective-C

I declare a class method:
+(int)widthScaled:(UIImage *)image maximumHeight:(int)max{
int width = 0;
width = (image.size.width - (((image.size.height - max)*100)/image.size.height)*image.size.width)/100;
return width;
}
In the same class, I declare an instance method like these:
- (void)generarVistas{
if(...){
...
}else{
for(...){
...
//I need to put the class method here but if I call the class method like this, don't recognize
int variable = [[self class] widthScaled:image maximumHeight:max];
...
}
}
I try to put the class method in instance method but doesn't work.
What context should I indicate to recognize the class method?
The problem you are facing is that [self class] is a runtime call who's return result is not known until runtime. The compiler doesn't know what class it is. The code you're writing must always be invoked from a fixed class, so don't do that. If the class is FooClass, then use this form:
int variable = [FooClass widthScaled:image maximumHeight:max];
(replace [self class] with your class name, e.g. FooClass.)

how to declare method which returns base Class

I would like to add a method which returns Class like below:
-(Class) validatorClass{
return [AddItemValidator class]; }
and use it like this:
self.validator = [[self validatorClass] alloc] initWithParentDirectory:self.parentDirectory];
How should I declare the return type -(Class) of this method to allow returning only classes which extend from defined class?
I would like to return something like -(Class<'NameValidator'>) where AddItemValidator extends from NameValidator.
How should I declare it?
As SomeGuy mentioned, you can't achieve compile-time safety in this case. Instead, you can use an assertion to have it checked at the runtime (better than nothing):
-(Class) validatorClass{
Class theClass = [AddItemValidator class];
NSAssert([theClass isSubclassOfClass:[NameValidator class]], #"Has to return subclass of %#", [NameValidator class]);
return theClass;
}
You can even go further and apply Factory pattern here to decouple validator class from the class being validated:
#implementation NameValidatorFactory
+(NameValidator*)validatorForObject:(YourObjectType*)validatedObject {
//choose proper validator depending on your object's type or anything you want
if([validatedObject isKindOfClass:[YourObjectTypeSuperclass class]]) {
return [AddItemValidator alloc];
}
else {
// handle other cases
}
}
And then create your validator like that:
self.validator = [[NameValidatorFactory validatorForObject:self] initWithParentDirectory:self.parentDirectory];

Resources