EzDevInfo.com

gh-unit

Test Framework for Objective-C

Unit testing private method - objective C

I use GHUnit. I want to unit test private methods and don't know how to test them. I found a lot of answers on why to or why not to test private methods. But did not find on how to test them.

I would not like to discuss whether I should test privates or not but will focus on how to test it.

Can anybody give me an example of how to test private method?


Source: (StackOverflow)

ARC, bridged cast and GHUnit

I'm followinng tutorial from http://gabriel.github.com/gh-unit/docs/appledoc_include/guide_testing.html. The problem is that my project uses ARC and GHUnit doesn't. I managed previous errors, but now i should do bridged cast, that i've never used, and i'm lost.

NSString *string1 = @"a string";
GHAssertNotNULL(string1, nil); //error here

Error description: Implicit conversion of Objective-C pointer type 'NSString *' to C pointer type 'const void *' requires a bridged cast.

Any help welcome :)


Source: (StackOverflow)

Advertisements

Unit testing IBOutlet's properties

I use GHUnit. I want to test IBOutlet's properties such as isHidden, delegate, etc.

I tried below code to test if myView is hidden :

- (void)testViewDidLoad
{
    // Call view on viewcontroller which will load the view if not loaded
    [testClass view];

    // Tests
    testClass.myView.hidden = YES;

    if (testClass.myView.isHidden) {
        GHTestLog(@"Hidden");
    }
    else {
        GHTestLog(@"Not Hidden");
    }
}

This always logs Not Hidden, whereas just before logging I set it hidden = YES.

Why is this?

To test delegate property of an IBOutlet I tried below line :

GHAssertNotNil(testClass.textField.delegate, @"delegate is nil.");

It fails with Reason : ((testClass.textField.delegate) != nil) should be FALSE.

What is wrong?

EDIT : Tried below code which does not work.

[testClass view];

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard"
                                         bundle:[NSBundle bundleForClass:[self class]]];
GHAssertNotNil(storyboard, nil);

// Tests
GHAssertTrue(testClass.myView.isHidden, nil);  // This fails

Source: (StackOverflow)

GHUnit access private variable

I'm trying to access a private class variable in my unit test:

Class
 - private variable abc;

unit test
category/extension above the unittest m file content
 @property (...) variable abc;

but within the test, I always get a unrecognized selector error... Is there any trick making private variables visible/testable?

Sorry, found nothing using google ;)

Greetings, matthias


Source: (StackOverflow)

iphone: cannot link gh-unit target to app target, cannot execute binary file

this is a question that tries to accomplish what this tutorial offers with a GHUnit Test Target. Its about linking a test target to the source target so that you dont have to manually include the source files in the test target. The following is an excerpt of the solution proposed.

Adding Unit Tests to an existing iOS project with Xcode 4

Project MyExistingApp -> + Add Target -> iOS -> Other -> Cocoa Unit Testing Bundle

Name the new target something like “Unit Tests” or “MyAppTests”

Select your new “Unit Tests” target and click the Build Phases tab, expand Target

Dependencies and add MyExistingApp as as a Target Dependency

Click the Build Settings tab and set the Bundle Loader setting to

$(BUILT_PRODUCTS_DIR)/MyExistingApp.app/MyExistingApp

Set the Test Host build setting to

$(BUNDLE_LOADER)

In your app target, set the Symbols Hidden by Default build setting to

NO

I get it to compile with a GHUnit Test Target following the tutorial, but I get a runtime error:

warning: This configuration supports "Darwin64" but is attempting to load
an executable of type i386 which is unlikely to work.
Attempting to continue.
`/usr/lib/dyld' has changed; re-reading symbols.
warning: Inconsistent DBX_SYMBOL_SIZE

/Users/...Tests.app/Tests: /Users...Tests.app/Tests: cannot execute binary file

Appreciate your help!

EDIT

I realize that there is a catch with the tutorial posted above and using GHUnit. The tutorial above assumes you are using OCUnit, wich launches a bundle loader target. The GhUnit target must however be an executable. If somebody wants to share how to link source files to an Executable target Ill appreciate it. For now, im going to do everything manually with GHUnit.


Source: (StackOverflow)

How start GHUnit tests without tapping Run button?

I use GHUnit framework for testing static library. At this moment I need tap the button Run to start my tests. But I would like to start tests when application launched because I need teamcity launch my testApp. So how can I modified standart UI and start tests automatic?


Source: (StackOverflow)

Unit test for NSManagedObject [GHUnit]

I am Java developer and I used to test my Java entity as POJO. Now, with Obj-C, I would like to do the same for my entity that inherit from NSManagedObject (I use CoreData for the persistence).

For example I would like to test my Customer entity as that :

-(void)myTest {
Customer *customer = [Customer alloc] init];
customer.name = @"toto";
GHAssertEqualStrings(customer.name, @"toto", @"");
}

But the error I encountered is :

NSInvalidArgumentException Reason: -[Customers setName:]: unrecognized selector sent to instance ...

So I have loaded all the NSManagedObjectContext in the setUp with the appropriate database schema url. Now I instantiate my customer as that and it works :

Customers *customer = [NSEntityDescription
insertNewObjectForEntityForName:kDataBaseCustomerKey inManagedObjectContext:ctx];

But is it an appropriate way to test a 'POJO'? I would like to test my Customer class without any model loading, because in this case I do not care of the datamodel.

Thank you for your suggestions.

Regards.


Source: (StackOverflow)

GHUnit target: failed to attach to process

I have a GHUnit test target, TestGH, which I'd like to use to test classes in my application, TestApp. I'm using Xcode 4.5 and trying to run TestGH on iPad 6.0 Simulator.

I believe I've configured the TestGH build correctly in the Build Settings and Build Phases. I've set the Target Dependencies to "TestApp" I've added the *.m files for the classes I'd like to test--along with the test case classes which will test them--to the Compile Sources section TestGH.

Other notable configuration:

In the app target, TestApp:

Symbols Hidden By Default: No
Product Name: TestApp

In the test target, TestGH:

Bundle Loader: $(BUILT_PRODUCTS_DIR)/TestApp.app/TestApp
Mach-O Type: Bundle
Other linker flags: -ObjC, -all_load
Product name: TestGH
Test Host: $(BUNDLE_LOADER)

I suppose I have this mostly right, as I discovered these settings by fighting through compile/link errors, reading stackoverflow, and blogs.

However, when I launch TestGH, the Log Navigator shows: error: failed to attach to process ID 2305 (2305 corresponds to 'sh' according to activity monitor, fyi)

Simulator screen remains black, and Xcode shows "Attaching to TestGH" in the status.

Any ideas?

I've gone through many suggested fixes/workarounds I've seen discussed here related to "failed to attach to process."

Deleted DerivedData folder in Library/Developer/Xcode, deleted everything under Library/Application Support/iPhone Simulator. Tried all the options under Product->Edit Scheme for the TestGH target--tried Debugger = GDB, LLDB, None, Launch = Automatically, wait. Results are always the same.


Source: (StackOverflow)

Unit Testing with GHUnit

I am new to iPhone Development. I have integrated the framework GHUnitIOS to Test my application. but I haven't found documentation about how to implement Unit testing (it's my first time in Unit Testing).

Can someone can help me to begin with GHUnit, documentations, examples, explanations?


Source: (StackOverflow)

GHUnit testing against an application that uses a library

I'm trying to build some GHUnit tests based on an iOS application I have which uses ProtocolBuffers, accessed as a library. I've run into lots of linker problems which I've slowly killed off by adding the source files from the application to the "Compile Sources" build phase, but now that I've added everything relevant in the application, I have found that I can't seem to link against ProtocolBuffers.

I have read GH-Unit for unit testing Objective-C code, why am I getting linking errors? wherein the poster seems to have fixed his situation based on the README update at the bottom. Since I have a hybrid - I am linking GHUnit against both an application and a library, I started with the assumption that I should add the ProtocolBuffers output as a dependency in addition to adding all the application source files to my "Compile Sources" build phase.

This hasn't worked. I continue to get linker errors which clearly show that the linker isn't finding symbols from the ProtocolBuffers library. I can't add the ProtocolBuffers source files because they're not in this project, and even adding #import "ProtocolBuffers.h" to my tests.pch file doesn't work.

I'm now stumped. Any suggestions? GHUnit looks great but, as it seems to always be with Xcode/ObjC testing tools, getting to "Hello World" is more trouble that I would expect.


Source: (StackOverflow)

GHAssertThrowsSpecific cannot find type NSRangeException

I'm using Xcode 4 and GHUnit to write some unit tests for the first time. All the advice appears to suggest going with GHUnit and not OCUnit.

I have a custom collection object called 'myList', and passing a message to get the selection at index:-1. It therefore correctly throws an NSRangeException (from the underlying mutable array).

I'm struggling to catch this with a GHAssertThrowsSpecific assertion.

This following line of code will not compile saying 'Unknown type name 'NSRangeException'.

GHAssertThrowsSpecific(s = [myList selectionAtIndex:-1],
            NSRangeException, @"Should have thrown an NSRangeException", nil);

I am #importing "Foundation/NSException.h" where NSRangeException appears to be defined. If I change it to:

GHAssertThrowsSpecific(s = [myList selectionAtIndex:-1],
            NSException, @"Should have thrown an NSException", nil);

then compiles fine and the assertion works, so its something to do with NSRangeException.

If I look in the headers, NSRangeException appears to be defined as a NSString * const in which case, how do I try to assert that I am expecting to catch it.

I'm obviously being quite dumb, as I can't see what I'm doing wrong.


Source: (StackOverflow)

GHUnit crashes when running assertion in callback block instead of showing error on front end

Using any assertion in a callback makes the GH-Unit app crash. Assertions work fine elsewhere.

There is a similar question here: Why does a false assertion in async test in GHUnit crash the app instead of just failing the test?

But I don't understand how I can use this solution in my case.

- (void)testLoadMyProfile {

    void(^successCallback)(NSString*);
    successCallback = ^(NSString* response) {

        NSRange textRange;
        textRange =[[response lowercaseString] rangeOfString:[@"syntactically incorrect" lowercaseString]];

        if(textRange.location != NSNotFound) {
            GHFail(@"the request was syntactically incorrect");
        }

        NSDictionary *d;        
        @try {
            d = [response JSONValue];    
        } @catch (NSException *exception) {
            GHAssertNotNil(d, @"The response was not a valid JSONValue");
        }

        GHAssertNotNil([d objectForKey:@"memberId"], @"memberId wasn't in response");
        GHAssertNotNil([d objectForKey:@"profile"], @"profile wasn't in response");
        GHAssertNotNil([d objectForKey:@"name"], @"profile wasn't in response");
        GHAssertNotNil([d objectForKey:@"surnamez"], @"profile wasn't in response");
    };

    void(^errorCallback)(NSString*);
    errorCallback = ^(NSString* response) {
        GHFail(@"the error callback was called");
    };    

    // this is using ASIHTTPRequest to retrieve data
    [[RestAPIConnector sharedInstance] loadMyProfile:successCallback :errorCallback];
}

I can stop the app from crashing by overwriting this method - I could even log the exception, but the test doesn't display as failed on the front end. Ideally, I'd like it to display on the front end so non technical people can run the test and see that everything is working.

- (void)failWithException:(NSException *)exception {

}

Source: (StackOverflow)

GHUnit gives allocate_pages() error after conversion to ARC in iOS Project

I've recently converted my iOS project to ARC. I have two targets in my project. One is the application itself, and the other is a set of GHUnit tests. I have approximately 200 tests that do quite a lot of work in terms of creating and modifying Core Data objects. The Core Data store used by the tests is an in memory store, and is thrown away once the tests are finished (i.e. it is not persisted anywhere).

When my tests have been running a while (they never reach the exact same point before the error is thrown, but it is always around the same tests) the application crashes with an EXC_BAD_ACCESS (Code=2, address=...)

The output in the console is as follows: Console Output

I've followed the instructions here in this answer, and set my main.m file of the GHUnit target to use the -fno-objc-arc compiler flag, but that doesn't seem to have helped.

I don't really understand what these errors mean, and searching for them doesn't seem to have helped. My only guess is that I am running out of memory, but I'm not sure why or how, considering ARC should be releasing objects for me.

I'd really appreciate any help anyone can give me to fix this! If you have any questions just leave me a comment and I will get back to you asap!

Thanks!


Source: (StackOverflow)

GH-Unit and Objective C++

I have an iPhone project that uses GHUnit to conduct unit testing. Recently, I've needed to implement complex numbers and overload some operators to ease the calculation of FFTs. The goal here was to create a clean way to perform an FFT without the overhead of all the possible functionality that libraries like FFTW uses, and in this sense, I could further customize the number of calculations I'd like to do in my FFT (so I reduce the complexity of factorizing this or that used in the traditional DFT).

In short, this is why I decided to implement my own FFT library in C++, rather than use FFTW. However, this has caused some problems with GHUnit. All of my production targets work correctly with the integration of my FFT library, but GHUnit refuses to work. Specifically, I get linker errors with things like GHComposeString. This only happens in my Unit Tests target. I'm wondering what this problem might be? At first, I suspected that this may be because of the differences in C vs C++ in how function names are mangled, but it doesn't seem to affect the rest of the project, just the GHUnit portions.

Any help with mixing C++ with GHUnit appreciated.


Source: (StackOverflow)

GHUnit error file _OBJC_CLASS_$_SenTestCase", referenced

I'm using GHUnit in my project but when i try to run the app it gives errors

Ld /Users/goldfire/Library/Developer/Xcode/DerivedData/WhatsMySpeed-amkgqintxyhelabqvrpouivmdglf/Build/Products/Debug-iphonesimulator/GHUnitTests.app/GHUnitTests normal i386 cd /Users/goldfire/Desktop/Example/WhatsMySpeed setenv MACOSX_DEPLOYMENT_TARGET 10.6 setenv PATH "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin" /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -arch i386 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator5.1.sdk -L/Users/goldfire/Library/Developer/Xcode/DerivedData/WhatsMySpeed-amkgqintxyhelabqvrpouivmdglf/Build/Products/Debug-iphonesimulator -F/Users/goldfire/Library/Developer/Xcode/DerivedData/WhatsMySpeed-amkgqintxyhelabqvrpouivmdglf/Build/Products/Debug-iphonesimulator -F/Users/goldfire/Desktop/Example/WhatsMySpeed -F/Applications/Xcode.app/Contents/Developer/Library/Frameworks -filelist /Users/goldfire/Library/Developer/Xcode/DerivedData/WhatsMySpeed-amkgqintxyhelabqvrpouivmdglf/Build/Intermediates/WhatsMySpeed.build/Debug-iphonesimulator/GHUnitTests.build/Objects-normal/i386/GHUnitTests.LinkFileList -mmacosx-version-min=10.6 -Xlinker -objc_abi_version -Xlinker 2 -ObjC -all_load -fobjc-arc -Xlinker -no_implicit_dylibs -D__IPHONE_OS_VERSION_MIN_REQUIRED=50100 -framework UIKit -framework Foundation -framework CoreGraphics -framework GHUnitIOS -framework SenTestingKit -o /Users/goldfire/Library/Developer/Xcode/DerivedData/WhatsMySpeed-amkgqintxyhelabqvrpouivmdglf/Build/Products/Debug-iphonesimulator/GHUnitTests.app/GHUnitTests

Undefined symbols for architecture i386: "_OBJC_CLASS_$_SenTestCase", referenced from: _OBJC_CLASS_$_LogicTests in LogicTests.o "_OBJC_METACLASS_$_SenTestCase", referenced from: _OBJC_METACLASS_$_LogicTests in LogicTests.o ld: symbol(s) not found for architecture i386 clang: error: linker command failed with exit code 1 (use -v to see invocation)


Source: (StackOverflow)