2015-02-03 6 views
7

신속하게 작업하고 있습니다. 페이지를 새로 고침하여 알림을 보내고 싶습니다. 하나의 ViewController에 알림을 게시하고 다른 뷰어에 관찰자를 추가하고 완벽하게 작업하고 있습니다. 내가하고 싶은 일은 신속하게 단위 테스트를 추가하는 것입니다. 많은 사이트를 확인했지만 할 수 없었습니다. 나는 신속하고 어디서부터 시작해야할지 모르겠다.NSNotification에 대한 단위 테스트 작성 방법

기본적으로 작업은 단추 알림을 클릭하면 다음보기 컨트롤러가로드 될 때 알림 관찰자가 추가됩니다.

가 어떻게 단위 테스트를 사전에

감사를 할 수

편집 :

NSNotificationCenter.defaultCenter().addObserver(self, selector: "vvv:",name:"notificationName", object: nil) 
+0

NSNotification''당신은 __don't__ 쓰기 단위 테스트. 클래스로 래핑하면 구성 요소의 조롱 가능/주사 가능 종속성이됩니다. –

+0

당신은 pls 몇 가지 코드를 줄 수 있습니다 .. 내가이 붙어 오전 .. – user2413621

+1

당신이 코드의 일부를 보여줄 수 있습니까? NSNotification을 어떻게 사용하고 있습니까? –

답변

8

일반적인 솔루션입니다 코드

NSNotificationCenter.defaultCenter().postNotificationName("notificationName", object: nil) 

및 추가 관찰자과 같이 사용 DI (Dependency Injection)를 사용하여 구성 요소를 단위 테스트 할 수있게합니다. 당신은 DI 프레임 워크를 사용할 수 있습니다 (Swift에 대한 좋은 프레임 워크가 있는지 아직 모르겠습니다). 네이티브 접근 방식을 사용합니다 (예 : 객체 전달)

가능한 한 접근법은 NSNotificationCenter을 랩핑하여 만드는 것입니다. 그것은 mockable/injectable.

이것은 의존성을 어떻게 분리 할 수 ​​있는지에 대한 기본적인 개념입니다. & 코드를 아래 코드를 붙여 넣지 않고 이해하지 않고 작동하게하십시오.

import Foundation 

protocol NotificationCenter { 
    func postNotificationName(name: String, object: AnyObject?) 

    // you can make it take the arguments as NSNotificationCenter.addObserver 
    func addObserver(callback: AnyObject? -> Void) 
} 

class MyNotificationCenter : NotificationCenter { 
    var _notificationCenter: NSNotificationCenter 

    init(_ center: NSNotificationCenter) { 
     _notificationCenter = center 
    } 

    func postNotificationName(name: String, object: AnyObject?) { 
     // call NSNotificationCenter.postNotificationName 
    } 

    func addObserver(callback: AnyObject? -> Void) { 
     // call NSNotificationCenter.addObserver 
    } 
} 

class MockNotificationCenter : NotificationCenter { 
    var postedNotifications: [(String, AnyObject?)] = [] 
    var observers: [AnyObject? -> Void] = [] 

    func postNotificationName(name: String, object: AnyObject?) { 
     postedNotifications.append((name, object)) 
    } 

    func addObserver(callback: AnyObject? -> Void) { 
     observers.append(callback) 
    } 
} 

class MyView { 
    var notificationCenter: NotificationCenter 

    init(notificationCenter: NotificationCenter) { 
     self.notificationCenter = notificationCenter 
    } 

    func handleAction() { 
     self.notificationCenter.postNotificationName("name", object: nil) 
    } 
} 

class MyController { 
    var notificationCenter: NotificationCenter 

    init(notificationCenter: NotificationCenter) { 
     self.notificationCenter = notificationCenter 
    } 

    func viewDidLoad() { 
     self.notificationCenter.addObserver { 
      println($0) 
     } 
    } 
} 

// production code 
// in AppDeletate.applicationDidFinishLaunching 
let notificationCenter = MyNotificationCenter(NSNotificationCenter.defaultCenter()) 

// pass it to your root view controller 
let rootViewController = RootViewController(notificationCenter: notificationCenter) 
// or 
rootViewController.notificationCenter = notificationCenter 

// in controller viewDidLoad 
self.myView.notificationCenter = self.notificationCenter 

// when you need to create controller 
// pass notificationCenter to it 
let controller = MyController(notificationCenter: notificationCenter) 

// in unit test 

func testMyView() { 
    let notificationCenter = MockNotificationCenter() 
    let myView = MyView(notificationCenter: notificationCenter) 
    // do something with myView, assert correct notification is posted 
    // by checking notificationCenter.postedNotifications 
} 

func testMyController() { 
    let notificationCenter = MockNotificationCenter() 
    let myController = MyController(notificationCenter: notificationCenter) 
    // assert notificationCenter.observers is not empty 
    // call it and assert correct action is performed 
} 
+0

을 확인합니다. 신속하게 새로운 질문을 던집니다. 코드 뒤에있는 기본 아이디어는 무엇입니까? – user2413621

+0

@ user2413621 google 및 의존성 주입을 배우십시오. 그것은 Swift와 아무 관련이없는 일반적인 프로그래밍 개념입니다. –

+0

은 내가 오류 유형을 얻고있다 'MyNotificationCenter'프로토콜을 준수하지 않는 'NotificationCenter'라인에하자 notificationCenter = MyNotificationCenter (NSNotificationCenter.defaultCenter()) // 다른 곳 할 MYVIEW = MYVIEW (notificationCenter : notificationCenter) – user2413621