4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

XCodeのUnitTestで、Failを赤く表示する

Last updated at Posted at 2013-01-27

====

XCodeColorsで、XCodeのコンソールに色が出せるようになるので、これを使ってUnitTestのFailを赤くするよう弄ってみました。

SenTestCase+PAMColor.h
//
//  SenTestCase+PAMColor.m
//  PAMColorUnitTest
//
//  Created by 田村 孝文 on 2013/01/27.
//  Copyright (c) 2013年 田村 孝文. All rights reserved.
//

# import "SenTestCase+PAMColor.h"
# import <objc/runtime.h>

// NSProxy 参考
// http://d.hatena.ne.jp/Kazzz/20120205/p1
@interface PAMColorExceptionProxy : NSProxy
@property(nonatomic,strong) NSException *targetException;
@end

@implementation PAMColorExceptionProxy
@synthesize targetException;

// "色付き"の文言を返す
- (NSString *)reason
{
    return [NSString stringWithFormat:@"\033[fg255,0,0;%@\033[;",
            self.targetException.reason];
}

- (void)forwardInvocation:(NSInvocation *)invocation
{
    if ( self.targetException )
    {
        [invocation setTarget:self.targetException];
        [invocation invoke];
    }
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel
{
    NSMethodSignature *result;
    if ( self.targetException )
    {
        result = [self.targetException methodSignatureForSelector:sel];
    }
    else
    {
        result = [super methodSignatureForSelector:sel];
    }    
    return result;
}
@end

@implementation SenTestCase (PAMColor)
+(void)load
{
    // failWithexceptionメソッドを入れ替える
    SEL originalSelector = @selector(failWithException:);
    SEL overrideSelector = @selector(swizz_failWithException:);
    
    Class clazz = [self class];
    Method originalMethod = class_getInstanceMethod(clazz, originalSelector);
    Method overrideMethod = class_getInstanceMethod(clazz, overrideSelector);
    
    method_exchangeImplementations(originalMethod, overrideMethod);
}

-(void)swizz_failWithException:(NSException *)exception
{
    // Proxyでラッピング
    PAMColorExceptionProxy *e = [PAMColorExceptionProxy alloc];
    e.targetException = exception;
    
    // method_exchangeImplementationsで「入れ替わってる」ので、
    // ↓でオリジナルメソッドを呼び出す
    [self swizz_failWithException:(NSException *)e];
}
@end
    STFail(@"Unit tests are not implemented yet in PAMColorUnitTestTests");


ちょっとしたHackでした。

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?