EzDevInfo.com

kiwi.js

Kiwi.js is a blazingly fast mobile & desktop browser based HTML5 game framework. It uses CocoonJS for publishing to the AppStore.

iOS Kiwi/Nocilla Tests not calling blocks

I am trying to get familar with the Kiwi BDD testing framework. I am using it it in conjuction with Nocilla to mock HTTP requests. Both projects look awesome but I am having some difficulty with it. I have the following test spec:

    beforeAll(^{ // Occurs once
         [[LSNocilla sharedInstance] start];
    });

    afterAll(^{ // Occurs once
        [[LSNocilla sharedInstance] stop];
    });

    beforeEach(^{ // Occurs before each enclosed "it"
        couch = [[Couch alloc]initWithDatabaseUrl:@"http://myhost/mydatabase"];
    });

    afterEach(^{ // Occurs after each enclosed "it"
        [[LSNocilla sharedInstance] clearStubs];
    });

    it(@"should be initialized", ^{
        [couch shouldNotBeNil];
    });

    context(@"GET requests", ^{
    it(@"should get document by id", ^{
        __block NSData *successJson = nil;
        __block NSError *requestErr = nil;
        stubRequest(@"GET", @"http://myhost/mydatabase/test").
        withHeader(@"Accept", @"application/json").
        withBody(@"{\"_id\":\"test\",\"_rev\":\"2-77f66380e1670f1876f15ebd66f4e322\",\"name\":\"nick\"");

        [couch getDocumentById:@"test" success:^(NSData *json){
            successJson = json;
        } failure:^(NSError *error) {
            requestErr = error;
        }];

        [[successJson shouldNot]equal:nil];

    });
    });

Sorry for the long code snippet. I want to make sure I give context. As you can see I am testing the behavior of an object which makes a GET request and reports the results in a 'success' block and reports errors in a 'failure' block. I have two __block vars to store success and failures receptively. Currently the test checks that the 'success' var has a value (not nil). This test passes. However debugging this test it appears neither blocks are ever executed. The successJson appears nil. I would expect Nocilla to have passed the stub body content to the success block parameter. So is my test constructed incorrectly?

Thanks!


Source: (StackOverflow)

How to test a UICollectionViewLayout with Kiwi?

I need to test a UICollectionViewFlowLayout subclass with Kiwi,

I have correctly mocked up the delegate and the dataSource for a UICollectionView, but I'm still having some issues.

With the specified item size of CGSize(200.0f, 200.0f), I should be getting 5 items on the screen, but for some reason the attributes array that is returned at the last line does return 10 attributes, so that means that there are 10 visible cells.

What could be going on here? If my layout works as expected there's always 5 elements on the screen:

This is what I have so far (read the comments), and it mostly works.

describe(@"LineLayout", ^{
    __block UICollectionView *collectionView;
    __block HICollectionViewLineLayout *layout;
    __block const CGRect windowFrame = CGRectMake(0.0f, 0.0f, 1024.0f, 768.0f);
    __block const CGSize itemSize = CGSizeMake(200.0f, 200.0f);

    // Create a Collection View that uses a LineLayout and set the datasource delegate
    // before each test
    beforeEach(^{
        layout = [[HICollectionViewLineLayout alloc] init];
        collectionView = [[UICollectionView alloc] initWithFrame:windowFrame collectionViewLayout:layout];

        // Mock the UILineLayout data source
        id delegateMock = [KWMock mockForProtocol:@protocol(UICollectionViewDelegateFlowLayout)];
        [[delegateMock should] conformToProtocol:@protocol(UICollectionViewDelegateFlowLayout)];
        [delegateMock stub:@selector(collectionView:layout:sizeForItemAtIndexPath:) andReturn:theValue(itemSize)];
        [delegateMock stub:@selector(collectionView:layout:insetForItemAtIndex:) andReturn:theValue(UIEdgeInsetsZero)];

        // Mock the UICollection View dataSource
        id dataSourceMock = [KWMock mockForProtocol:@protocol(UICollectionViewDataSource)];
        [[dataSourceMock should] conformToProtocol:@protocol(UICollectionViewDataSource)];
        [dataSourceMock stub:@selector(numberOfSectionsInCollectionView:) andReturn:theValue(1)];
        [dataSourceMock stub:@selector(collectionView:numberOfItemsInSection:) andReturn:theValue(10)];

        // Set the delegate and the data source
        collectionView.delegate = delegateMock;
        collectionView.dataSource = dataSourceMock;

        // Reload the collectionView Data
        [collectionView reloadData];
    });

    it(@"Should properly identify central element when cell number is not even", ^{
        NSArray *attributes = [layout layoutAttributesForElementsInRect:windowFrame];

        // test that [attributes count] == 5
    });

This is what I see when I just run the app with no tests:

enter image description here


Source: (StackOverflow)

Advertisements

How do I test categories using Kiwi

I am having problems when using Kiwi to test a dynamically linked framework. The issue is that my objects do not respond to selectors of the functions defined in categories in my dynamically linked framework.

I initially thought that this was a problem with my build settings so I created a fresh project here : https://github.com/dreid93/TestingFrameworkCategory

In this project I have created a category called GenericCategory and have written three tests. One in Objective-C using XCTest, one in Swift using XCTest and the final in Objective-C using Kiwi. The XCTest tests are passing while the Kiwi test is failing.

I have added the -all_load and -ObjC flags to the Other Linker Flags in the build settings of the test target and this did not resolve the problem.

I have also taken a look at the following article though it did not offer any solutions : http://adoptioncurve.net/archives/2012/09/test-driven-development-of-an-objective-c-category-with-kiwi/

Thanks in advance for any and all help.


Source: (StackOverflow)

How to use kiwi to test the parameters of function call?

I can use the following code to test that cruiser has been called twice. But how to test that the parameter of first call is 7, and the param of second call is 8?

id cruiser = [Cruiser cruiser];
[[cruiser should] receive:@selector(energyLevelInWrapCore:) withCount:2];
[cruiser energyLevelInWarpCore:7];
[cruiser energyLevelInWarpCore:8];

And is it possible to get the parameter after the method is called? Like the following code.

id cruiser = [Cruiser cruiser];
[cruiser stub:@selector(energyLevelInWarpCore:)];
[cruiser energyLevelInWarpCore:7];
[cruiser energyLevelInWarpCore:8];
[[[[[cruiser stub] calles][1] arguments][0] should] equal:theValue(8)]; // This doesn't work

Source: (StackOverflow)

XCTest linker error for custom cocoa touch framework

I created a custom cocoa touch framework, the custom touch framework uses Kiwi pod and thus uses XCTest.

In my framework target I ensured there are no linker flags for XCTest and I Archived the framework and added that to a new project.

In the new project the app builds and upon launch I get this message.

dyld: Library not loaded: @rpath/XCTest.framework/XCTest referenced from the framework I added.

I am not sure why the library is still linking to XCTest.


Source: (StackOverflow)

Capture arguments of static method calls using Kiwi

This link shows how to capture an argument of a mock object using Kiwi.

Is there a way to capture arguments of static method calls? It seems to me that this only work with instance methods.


Source: (StackOverflow)

Kiwi and CocoaPods with a static shared library

I have a workspace with 3 projects:

  • MyApp
  • Common
  • Pods

Common is a common library that MyApp depends on. I'd like to setup CocoaPods and Kiwi to work correctly in this project. How do I go about this?

I found http://stackoverflow.com/a/16472563/62, but when I try to follow this approach, I get an error when building MyApp before I even try adding Kiwi:

ld: library not found for -lPods

Here's the repo on GitHub: https://github.com/lyahdav/cocoapods_kiwi_shared_library

My Podfile is:

workspace 'MyApp.xcworkspace'
platform :ios, '7.0'

target 'Common' do
  xcodeproj 'Common/Common.xcodeproj'

  pod 'AFNetworking'
  pod 'Reachability'

  target 'MyApp', :exclusive => true do
    xcodeproj 'MyApp.xcodeproj'
  end
end

Source: (StackOverflow)

Global helper for Kiwi specs

I've defined some helper blocks within the BEGIN_SPEC END_SPEC block in my spec file that I reuse quite often. E.g. asserting that a certain dialog shows up:

void (^expectOkAlert) (NSString *, NSString *) = ^void(NSString *expectedTitle, NSString *expectedMessage) {
    UIAlertView *alertView = [UIAlertView mock];
    [UIAlertView stub:@selector(alloc) andReturn:alertView];
    [[alertView should] receive:@selector(initWithTitle:message:delegate:cancelButtonTitle:otherButtonTitles:)
                      andReturn:alertView
                  withArguments:expectedTitle,expectedMessage,any(),@"OK",any()];
    [[alertView should] receive:@selector(show)];
};

I'd like to reuse this block over several other spec files. Is that somehow possible like we normally do it with spec helpers and rspec in the Ruby world?

How do you manage you global spec helpers?


Source: (StackOverflow)

Is there a workaround for the lack of a verify method on Kiwi mocks?

I have a strong preference for a highly predictable Arrange Act Assert format for unit tests.

Because Kiwi doesn't have an explicit verify statement for mocks, it forces a different pattern, something like:

// Arrange
Thing *mockThing = [CollaboratingClass mock];
TestedClass *sut = [[TestedClass alloc] initWithCollaborator:mockThing];

// Expect (collaboration expectations)
[[[mockThing should] receive] someMessage];

// Act
[mockArray someMethodInvolvingCollaborator];

// Assert (state expectations)
[[sut.someProperty should] equal:someValue];

I know that the verification happens anyway, but prefer to be able to quickly scan tests, with assertions and expectations being together in one predictable place. This is nicely enabled by mockito (and its Objective-C implementation OCMockito), where the verification step specifies the method call post-hoc, making a prior expectation step unnecessary.

I'm a relative Kiwi novice, so I may have missed something in the docs. Is there a way of explicitly verifying Kiwi mocks?


Source: (StackOverflow)

How does one unit test code that interacts with the Core Bluetooth APIs?

I would like to unit test a class that acts as a CBPeripheralManagerDelegate to the CBPeripheralManager class. Typically, in order to stub out an external class dependency, I would use either a form of dependency injection by passing in via the class initializer or via a property. When dealing with singleton-based API's, I have been able to use libraries like Kiwi to stub the class level method that returns the singleton (i.e. [ClassName stub:@selector(sharedInstance) andReturn:myStubbedInstance]). The issue in the case of mocking CBPeripheralManager is that its initializer takes the delegate instance. So any code that uses my class would need to do something like this:

PeripheralManagerWrapper *wrapper = [[PeripheralManagerWrapper alloc] init];
CBPeripheralManager *peripheralManager = [[CBPeripheralManager alloc] initWithDelegate:wrapper queue:nil options:nil];
wrapper.peripheralManager = peripheralManager;

Then, for unit testing my PeripheralManagerWrapper class, I could simply instantiate it and pass in a mocked CBPeripheralManager. However, I don't like requiring any calling code of my wrapper object to have to go through this setup. Is there a better pattern for dealing with this situation? I've used both Kiwi and OCMockito, but neither seem to provide this functionality short of maybe stubbing the alloc and init methods of CBPeripheralManager and then just instantiating the instance in the PeripheralManagerWrapper 's initializer.


Source: (StackOverflow)

How to test AFNetworking

*Edit - I originally wanted to test AFNetworking using Nocilla but ended up using OHHTTPStubs to do the job. I've answered the original question below, using OHHTTPStubs *

Original Question:

I want to test the APIClient of our app - the bare bones of one of methods which needs to be tested is detailed below. So I need to mimic the HTTPRequestOperationWithRequest: call from AFNetworking. Nocilla seems like an option to do this (more suitable than OCMock). I've checked out the github page which deals with Nocilla and AFNetworking but I'm not sure how to apply it to my problem - the syntax isn't very familiar.

  • So my wondering if someone could give me a hint as to how I might use Nocilla in this case?
  • Also, must one use Kiwi with Nocilla?

Thanks in advance :)

    -(AFHTTPRequestOperation *)getBroadcastsForChannel:(TINChannel *)channel
                                     startTime:(NSDate *)date
                                         limit:(NSNumber *)limit
                                     pastLimit:(NSNumber *)pastLimit
                                        fields:(NSArray *)fieldsArray
                                      interval:(TINBroadcastsInterval)interval
                               completionBlock:(void (^)(NSArray *broadcasts, NSError *error))block {

    // Some setup here

    NSURLRequest *request = [self requestWithMethod:@"GET" path:path parameters:params];

    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {

    NSError *error;

    NSDictionary *responseDic = [self parseResponse:responseObject error:&error];

        if (error) {
            if (block) {
                block([NSArray array], error);
            }
            return;
        }

        // Parse the response object here

        if (block) {
            block([NSArray arrayWithArray:broadcastsOutput], nil);
        }

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    if (block) {
        block([NSArray array], error);
    }
    }];

        [self enqueueHTTPRequestOperation:operation];

        return operation;

}

Source: (StackOverflow)

How to unit test api calls using AFNetworking

I have an iOS app I'm working on, which connects to a third-party web service. I have around 50 different calls, and want to write unit tests using Kiwi, but I have no idea where to start.

As I'm not responsible for the API, I need to just check that my calls are pointing to the correct URL, using the correct GET or POST method.

Is there any way to test this properly?

Heres an example of one of my calls:

+ (void)listsForUser:(NSString *)username
            response:(void (^)(NSArray *lists))completion
{
    NSString *path = [NSString stringWithFormat:@"user/list.json/%@/%@", TRAKT_API_KEY, username];
    [TNTraktAPIManager requestWithMethod:GET
                                    path:path
                              parameters:nil
                                callback:^(id response) {
                                    completion(response);
                                }];
}

Which calls the following helper method

+ (void)requestWithMethod:(HTTPMethod)method
                     path:(NSString *)path
               parameters:(NSDictionary *)params
                 callback:(void (^)(id response))completion
{
    NSString *methodString = @"POST";
    if (method == GET) {
        methodString = @"GET";
    }


    // Setup request
    NSURLRequest *request = [[TraktAPIClient sharedClient] requestWithMethod:methodString
                                                                        path:path
                                                                  parameters:params];

    // Setup operation
    AFJSONRequestOperation *operation =
    [AFJSONRequestOperation JSONRequestOperationWithRequest:request
                                                    success:^(NSURLRequest *request,
                                                              NSHTTPURLResponse *response,
                                                              id JSON) {
                                                        id jsonResults = JSON;
                                                        completion(jsonResults);

                                                    } failure:^(NSURLRequest *request,
                                                                NSHTTPURLResponse *response,
                                                                NSError *error,
                                                                id JSON) {

                                                        id jsonResults = JSON;
                                                        completion(jsonResults);
                                                        NSLog(@"%s: error: %@", __PRETTY_FUNCTION__, error);

                                                    }];
    // TODO: Queue operations
    [operation start];

}

Source: (StackOverflow)

Strange ordering of Kiwi iOS context blocks

I have a Kiwi spec file that looks something like this:

#import "Kiwi.h"
#import "MyCollection.h"

SPEC_BEGIN(CollectionSpec)

describe(@"Collection starting with no objects", ^{
    MyCollection *collection = [MyCollection new];

    context(@"then adding 1 object", ^{
        MyObject *object = [MyObject new];
        [collection addObject:object];
        it(@"has 1 object", ^{
            [collection shouldNotBeNil];
            [collection.objects shouldNotBeNil];
            [[theValue(collection.objects.count) should] equal:theValue(1)]; //failing test
        });

        context(@"then removing 1 object", ^{
            [collection removeObject:object];
            it(@"has 0 objects", ^{
                [[theValue(collection.objects.count) should] equal:theValue(0)]; //passing test
            });
        });
    });
});

SPEC_END

Running the spec results in one failure at this line of code [[theValue(collection.objects.count) should] equal:theValue(1)];

Here's the strange part - if I remove the whole context(@"then removing 1 object", ^{...}) block from the spec the aforementioned test passes.

This leads me to believe that the [collection removeObject:object] line is getting executed before the failing test. I have a feeling I may be misunderstanding the order that blocks are executed in.

Any suggestions would be appreciated!


Source: (StackOverflow)

How to deal with Kiwi? Can't run first tests (Installed via Cocoapods)

I'm trying to run my first Kiwi tests. I use Xcode 5 and Kiwi 2.0 for iOS (installed via Cocoapods). I wrote some tests but when I press 'cmd+u' output in console look like following:

Log

2013-09-25 19:17:04.347 KiwiPro[36355:a0b] Cannot find executable for CFBundle 0xc1665d0 </Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator7.0.sdk/System/Library/AccessibilityBundles/CertUIFramework.axbundle> (not loaded)
Test Suite 'All tests' started at 2013-09-25 17:17:04 +0000
Test Suite 'All tests' finished at 2013-09-25 17:17:04 +0000.
Executed 0 tests, with 0 failures (0 unexpected) in 0.000 (0.001) seconds

Test:

#import "Kiwi.h"
#import "Person.h"

SPEC_BEGIN(MySpec)

describe(@"When Person born", ^{
    Person *person = [Person new];
    it(@"Should be age of 0", ^{
    [[theValue([person age]) should] equal:theValue(0)];
    });
});

SPEC_END

And here is Podfile

platform :ios, '6.0'

target :KiwiProTests, :exclusive => true do
    pod 'Kiwi', '~> 2.0'
end

I think that tests aren't compiled. In linke below my project with Kiwi and test are available.

Project on dropbox

https://dl.dropboxusercontent.com/u/11493275/Tmp/KiwiPro.zip

Thank you in advance.


Source: (StackOverflow)

Examining a method argument on a mock object with Kiwi

I need help with the following: I'm writing some BDD tests for an client API with the following structure:

@protocol MyAPIClientDelegate <NSObject>
  -(void)myCallbackMethod:(id)response;
@end

// BEGIN: MyAPIClientSpec.h

SPEC_BEGIN(MyAPIClientSpec)

describe(@"MyAPIClientAPI ", ^{
    __block MyAPI *api = nil;
    __block id delegateMock = nil;

    beforeEach(^{
        delegateMock = [KWMock mockForProtocol:@protocol(MyAPIClientDelegate)];
        api = [MyAPI APIClientWithDelegate:delegateMock];
    });

    afterEach(^{
        delegateMock = nil;
        api = nil;
    });

    it(@"should return a JSON { result: 'ok', token: <SOME_TOKEN> }", ^{
        [[api should] receive:@selector(myMethodCall:)];

        [[[delegateMock shouldEventually] receive] myCallbackMethod:any()];

        [api myMethodCall];
    });
});

SPEC_END

As you can see in the code above, I'm using any() to check that at least there is a parameter sent to the delegate.

Is there anyway to define a function (or objective-c block) to check the parameter?

Thanks!


Source: (StackOverflow)