Error while unit testing Google Analytics tracker in XCode 6
I am writing a unit test to check that the string passed to the class GAITracker
is returned as a property kGAIScreenName
for each screen.
However, when I try to pass sharedInstance
to a class GAI
to initialize an instance WNGoogleAnalyticsService
, I get an error Thread 1: EXC_BAD_ACCESS (code=1, address=0x20)
as if it was not allocated for memory. No matter where I try to declare sharedInstance will not initialize in the test class, although it works fine in AppDelegate.m
.
WNGoogleAnlayticsServiceTest.m:
-(void)testIfNoScreenNameExists {
NSString *screenName = @"Screen";
Class builder = [GAIDictionaryBuilder class];
GAI *gai = [GAI sharedInstance];
WNGoogleAnalyticsService *s = [[WNGoogleAnalyticsService alloc] initWithGAInstance:gai
gaKey:@"test"
gaDictionaryBuilderClass:builder
debugging:NO];
id<GAITracker> tracker = [s trackerForScreen:screenName];
XCTAssertEqualObjects([tracker get:kGAIScreenName], screenName);
}
AppDelegate.m:
Add Google Analytics as analytics service
WNGoogleAnalyticsService *googleAnalyticsService = [[WNGoogleAnalyticsService alloc] initWithGAInstance:[GAI sharedInstance]
gaKey:[[NSBundle mainBundle] objectForInfoDictionaryKey:@"WNGoogleKey"]
gaDictionaryBuilderClass:[GAIDictionaryBuilder class]
debugging:analyticsDebugging];
I don't understand how to even go about fixing this error, so any help would be appreciated.
source to share
As per the comment I left behind my question, I feel like I should officially answer this with my solution.
In the case of this unit test, I was trying to reuse the singleton by reusing the method in [GAI SharedInstance]
both my WNGoogleAnlayticsServiceTest and my AppDelegate.m file, which by definition it cannot do.
So, if you want to test Google Analytics methods, you should use a tool like OCMock to do this, as you cannot initialize sharedInstance twice.
source to share