MiniMockServer 0.1.2

MiniMockServer 0.1.2

Ngoc Le维护。



MiniMockServer是一个Swift框架,为iOS上的UI/集成测试提供了对API请求进行模拟的简单解决方案。

灵感来源

此库基于Jodel的iOS开发者Michael在这篇文章中的代码
https://jodel.com/engineering/dynamic-http-mocking/

安装

使用Cocoapods

  pod 'MiniMockServer', '0.1.0'

使用方法

  • 通过覆盖initialStubs方法来设置初始请求的响应。
  override func initialStubs() -> [HTTPStubInfo]? {
        let fakeVolumes: [[String: Any]] = []
        return [
            HTTPStubInfo(path: "/volumes?q=Harry%20Potter",
                         method: .GET,
                         response: .successObject(object: fakeVolumes))
        ]
    }
  • 在任何位置调用存根函数以覆盖之前的存根
    func testExample() {
        let bundle = Bundle(for: type(of: self))
        guard let fileUrl = bundle.url(forResource: "search_books", withExtension: "json") else {
            XCTFail("Mock file is not exist.")
            return
        }

        stub(path: "/volumes?q=mockserver", response: .successFile(fileUrl: fileUrl))

        let textFieldSearch = app.textFields["textFieldSearch"]
        XCTAssert(waitForElementToAppear(textFieldSearch))
        textFieldSearch.clearAndEnterText("mockserver")

        textFieldSearch.typeText(XCUIKeyboardKey.return.rawValue)

        let collectionView = app.collectionViews.element(boundBy: 0)
        let firstCell = collectionView.cells.element(boundBy: 0)
        XCTAssert(waitForElementToAppear(firstCell))

        let publisherLabel = firstCell.staticTexts["publisherLabel"]
        XCTAssertEqual(publisherLabel.label, "Published by: Mock Server")
    }
  • 使用json文件进行存根响应
    let bundle = Bundle(for: type(of: self))
    guard let fileUrl = bundle.url(forResource: "search_books", withExtension: "json") else {
        XCTFail("Mock file is not exist.")
        return
    }

    stub(path: "/volumes?q=mockserver", response: .successFile(fileUrl: fileUrl))
  • 使用对象(数组或字典)进行存根响应
    let fakeVolumes: [[String: Any]] = []
    stub(path: "/volumes?q=mockserver", response: .successObject(object: fakeVolumes))
  • 存根错误
    stub(path: "/auth/sms-request-code",
        method: .GET,
        statusCode: 401,
        response: .error(rootCause: "Service not available",
                      errorMessage: "Unfortunately our service is not available at the moment. Please try again later."))

许可证

MiniMockServer在MIT许可证下发布。有关详细信息,请参阅LICENSE