简体   繁体   English

单元测试用例-Swift 3.2

[英]Unit test cases - Swift 3.2

I have to write unit test case to check whether a particular method gets called or not from within the method which is being called from unit test case. 我必须编写单元测试用例,以检查是否从单元测试用例中调用的方法中调用了特定方法。

class A{
    func fetchPersonsData() {
       let b = B()
       b.sendDataToserver([])
     }
}

class B {
  func sendEventToServer(_:[]) {
  }
}

In my unit test case I will call fetchPersonsData() method and want to check whether it calls sentEventToServer(_:) or not and what are the params. 在我的单元测试用例中,我将调用fetchPersonsData()方法并希望检查它是否调用sentEventToServer(_:)以及参数是什么。

How to write test case for this in Swift 3.2? 如何在Swift 3.2中为此编写测试用例?

Should I mock by creating subclass of class B and override required method and pass my test if required method gets called? 我是否应该通过创建类B的子类来模拟并覆盖必需的方法,并在调用必需的方法时通过测试?

First add a protocol: 首先添加一个协议:

protocol ServerSender {
    func sendEventToServer(_:[String])
}

Make B conform to that protocol: 使B符合该协议:

class B: ServerSender {
    func sendEventToServer(_:[String]) {
    }
}

In your test target add a mock: 在测试目标中添加一个模拟:

class BMock: ServerSender {
    var sendDataToServerCalled = false
    func sendEventToServer() {
        sendDataToServerCalled = true
    }
}

Change A to allow dependency injection: 更改A以允许依赖项注入:

class A {
    lazy var b: ServerSender = B()
    func fetchPersonsData() {
        b.sendDataToServer([])
    }
 }

In your test, inject the mock: 在测试中,注入模拟:

func test_fetchPersonsData_sendsDataToServer() {
    let sut = A()
    let mock = BMock()
    sut.b = mock

    a.fetchPersonsData()

    XCTAssertTrue(mock.sendDataToServerCalled)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM