自动化Test使用详细解析(五) —— 单元测试和UI Test(二)

版本记录

版本号 时间
V1.0 2020.06.23 星期二

前言

自动化Test可以通过编写代码、或者是记录开发者的操作过程并代码化,来实现自动化测试等功能。接下来几篇我们就说一下该技术的使用。感兴趣的可以看下面几篇。
1. 自动化Test使用详细解析(一) —— 基本使用(一)
2. 自动化Test使用详细解析(二) —— 单元测试和UI Test使用简单示例(一)
3. 自动化Test使用详细解析(三) —— 单元测试和UI Test使用简单示例(二)
4. 自动化Test使用详细解析(四) —— 单元测试和UI Test(一)

源码

1. Swift

首先看下工程组织结构

下面就是测试部分源码了

1. AmountFormatter.swift
import Foundation

enum AmountFormatter {
  private static let amountFormatter: NumberFormatter = {
    let formatter = NumberFormatter()
    formatter.minimumFractionDigits = 2
    formatter.maximumFractionDigits = 2
    return formatter
  }()

  static func string(from decimal: Decimal) -> String? {
    return amountFormatter.string(from: decimal)
  }

  static func decimal(from string: String) -> Decimal? {
    return amountFormatter.number(from: string)?.decimalValue
  }
}

extension NumberFormatter {
  func string(from decimal: Decimal) -> String? {
    return self.string(from: decimal as NSDecimalNumber)
  }
}
2. Account.swift
import Foundation

struct Account {
  let name: String
  var balance: Decimal = 0.0

  mutating func updateBalance(by amount: Decimal) {
    balance += amount
  }
}
3. AccountsView.swift
import SwiftUI

struct AccountsView: View {
  @ObservedObject private var viewModel = AccountsViewModel()

  init() {
    UITableView.appearance().separatorStyle = .none
  }

  var body: some View {
    NavigationView {
      List {
        ForEach(viewModel.accounts.indices, id: \.self) { index in
          // swiftlint:disable:next multiline_arguments
          NavigationLink(destination: UpdateBalanceView {
            self.viewModel.updateBalance(at: index, by: $0)
          }) {
            AccountView(account: self.viewModel.accounts[index])
          }
        }
        .onDelete(perform: delete)
      }
      .navigationBarTitle("BudgetKeeper")
      // swiftlint:disable:next multiple_closures_with_trailing_closure
      .navigationBarItems(trailing: Button(action: {}) {
        // swiftlint:disable:next multiline_arguments
        NavigationLink(destination: CreateAccountView {
          self.viewModel.create(account: $0)
        }) {
          Image("add")
        }
      }.accessibility(identifier: "add_account"))
    }
    .accentColor(Color.init("violet"))
  }

  private func delete(at offsets: IndexSet) {
    viewModel.delete(at: offsets)
  }
}

struct ContentView_Previews: PreviewProvider {
  static var previews: some View {
    AccountsView()
  }
}
4. AccountsViewModel.swift
import SwiftUI

final class AccountsViewModel: ObservableObject {
  @Published private(set) var accounts: [Account] = []

  func create(account: String) {
    accounts.append(Account(name: account))
  }

  func delete(at offsets: IndexSet) {
    accounts.remove(atOffsets: offsets)
  }

  func updateBalance(at index: Int, by amount: Decimal) {
    accounts[index].updateBalance(by: amount)
  }
}
5. AccountView.swift
import SwiftUI

struct AccountView: View {
  let account: Account

  private var balanceString: String {
    // 3
    let amount = AmountFormatter.string(from: abs(account.balance)) ?? ""
    let balance = currencySymbol + amount
    return account.balance < 0 ? "-" + balance : balance
  }

  // 1
  private var currencySymbol: String {
    // 2
    return Locale.current.currencySymbol ?? ""
  }

  private let gradient = LinearGradient(
    gradient: Gradient(colors: [Color.init("violet"), Color.init("purple")]),
    startPoint: .leading,
    endPoint: .trailing)

  var body: some View {
    HStack {
      Text(account.name)
        .font(.headline)
        .padding()
        .foregroundColor(Color.white)
      Spacer()
      Text(balanceString)
        .font(.title)
        .foregroundColor(Color.white)
        .padding()
        .lineLimit(1)
    }
    .background(gradient)
    .cornerRadius(10)
    .shadow(color: Color.black.opacity(0.2), radius: 3, x: 0, y: 2)
  }
}

struct AccountView_Previews: PreviewProvider {
  static var previews: some View {
    AccountView(account: Account(name: "Savings"))
  }
}
6. UpdateBalanceView.swift
import SwiftUI

struct UpdateBalanceView: View {
  var onBalanceUpdated: (Decimal) -> Void

  @Environment(\.presentationMode) private var presentationMode: Binding
  @State private var input: String = ""

  var body: some View {
    NavigationView {
      VStack {
        TextField("0.00", text: $input)
          .keyboardType(.numbersAndPunctuation)
          .lineLimit(1)
          .font(.largeTitle)
          .padding()
          .multilineTextAlignment(.center)
        Button(action: save) {
          Text(NSLocalizedString("Save", comment: ""))
        }.accessibility(identifier: "save")
        Spacer()
      }
    }
    .accentColor(Color.init("violet"))
    .navigationBarTitle("Update Balance")
  }

  private func save() {
    let sum = AmountFormatter.decimal(from: input)
    onBalanceUpdated(sum ?? 0)
    presentationMode.wrappedValue.dismiss()
  }
}

struct UpdateBalanceView_Previews: PreviewProvider {
  static var previews: some View {
    UpdateBalanceView {
      print($0)
    }
  }
}
7. CreateAccountView.swift
import SwiftUI

struct CreateAccountView: View {
  var onAccountCreated: (String) -> Void

  @Environment(\.presentationMode) private var presentationMode: Binding
  @State private var input: String = ""

  var body: some View {
    NavigationView {
      VStack {
        TextField(NSLocalizedString("Enter the name", comment: ""), text: $input)
          .lineLimit(1)
          .font(.largeTitle)
          .padding()
          .multilineTextAlignment(.center)
        Button(action: save) {
          Text(NSLocalizedString("Save", comment: ""))
        }.accessibility(identifier: "save")
        Spacer()
      }
    }
    .accentColor(Color.init("violet"))
    .navigationBarTitle("New Account")
  }

  private func save() {
    onAccountCreated(input)
    presentationMode.wrappedValue.dismiss()
  }
}

struct CreateAccountView_Previews: PreviewProvider {
  static var previews: some View {
    CreateAccountView {
      print($0)
    }
  }
}
8. AccountsViewModelUnitTest.swift
import XCTest
@testable import BudgetKeeper

class AccountsViewModelUnitTest: XCTestCase {
  func testAccountsListEmpty() {
    let viewModel = AccountsViewModel()

    XCTAssertTrue(viewModel.accounts.isEmpty)
  }

  func testAddNewAccount() {
    let viewModel = AccountsViewModel()

    viewModel.create(account: "Debit card")

    XCTAssertEqual(viewModel.accounts.count, 1)
    XCTAssertEqual(viewModel.accounts.first?.name, "Debit card")
    XCTAssertEqual(viewModel.accounts.first?.balance, 0)
  }

  func testDeleteAccount() {
    let viewModel = AccountsViewModel()
    viewModel.create(account: "Salary")

    viewModel.delete(at: IndexSet(arrayLiteral: 0))

    XCTAssertTrue(viewModel.accounts.isEmpty)
  }

  func testUpdateBalance() {
    let viewModel = AccountsViewModel()
    viewModel.create(account: "Savings")

    viewModel.updateBalance(at: 0, by: -300)

    XCTAssertEqual(viewModel.accounts.first?.balance, -300)

    viewModel.updateBalance(at: 0, by: 450)

    XCTAssertEqual(viewModel.accounts.first?.balance, 150)
  }

  func testMultipleAccounts() {
    let viewModel = AccountsViewModel()

    viewModel.create(account: "Salary")
    viewModel.create(account: "Credit card")
    viewModel.create(account: "Savings")

    viewModel.delete(at: IndexSet(arrayLiteral: 1))
    viewModel.updateBalance(at: 1, by: 150)

    XCTAssertEqual(viewModel.accounts.count, 2)
    XCTAssertEqual(viewModel.accounts.map { $0.name }, ["Salary", "Savings"])
    XCTAssertEqual(viewModel.accounts[0].balance, 0)
    XCTAssertEqual(viewModel.accounts[1].balance, 150)
  }
}
9. AccountsViewUITest.swift
import XCTest

class AccountsViewUITest: XCTestCase {
  let app = XCUIApplication()
  let currency = Locale.current.currencySymbol ?? "$"
  let separator = Locale.current.decimalSeparator ?? "."

  override func setUpWithError() throws {
    continueAfterFailure = false
    app.launch()
  }

  func testAddAccount() {
    app.buttons["add_account"].tap()

    XCTAssertEqual(app.navigationBars.staticTexts.firstMatch.label, localizedString("New Account"))

    app.textFields.firstMatch.tap()
    app.textFields.firstMatch.typeText("Savings")
    app.buttons["save"].tap()

    XCTAssertEqual(app.cells.count, 1)
    // since the cell content is wrapped into the navigation link, the element type is 'button'
    XCTAssertEqual(app.cells.buttons.firstMatch.label, "Savings\n\(currency)0\(separator)00")
  }

  func testDeleteAccount() {
    app.buttons["add_account"].tap()
    app.textFields.firstMatch.tap()
    app.textFields.firstMatch.typeText("Savings")
    app.buttons["save"].tap()

    let cell = app.cells.firstMatch
    cell.swipeLeft()
    cell.buttons.firstMatch.tap()

    XCTAssertEqual(app.cells.count, 0)
  }

  func testUpdateBalance() {
    app.buttons["add_account"].tap()
    app.textFields.firstMatch.tap()
    app.textFields.firstMatch.typeText("Savings")
    app.buttons["save"].tap()

    app.cells.firstMatch.tap()

    XCTAssertEqual(app.navigationBars.staticTexts.firstMatch.label, localizedString("Update Balance"))

    app.textFields.firstMatch.tap()
    app.textFields.firstMatch.typeText("-120")
    app.buttons["save"].tap()

    XCTAssertEqual(app.cells.buttons.firstMatch.label, "Savings\n-\(currency)120\(separator)00")

    app.cells.firstMatch.tap()
    app.textFields.firstMatch.tap()
    app.textFields.firstMatch.typeText("340")
    app.buttons["save"].tap()

    XCTAssertEqual(app.cells.buttons.firstMatch.label, "Savings\n\(currency)220\(separator)00")
  }

  func testMultipleAccounts() {
    app.buttons["add_account"].tap()
    app.textFields.firstMatch.tap()
    app.textFields.firstMatch.typeText("Savings")
    app.buttons["save"].tap()

    app.buttons["add_account"].tap()
    app.textFields.firstMatch.tap()
    app.textFields.firstMatch.typeText("Salary")
    app.buttons["save"].tap()

    app.cells.firstMatch.tap()
    app.textFields.firstMatch.tap()
    app.textFields.firstMatch.typeText("7620")
    app.buttons["save"].tap()

    app.cells.element(boundBy: 1).tap()
    app.textFields.firstMatch.tap()
    app.textFields.firstMatch.typeText("5455")
    app.buttons["save"].tap()

    XCTAssertEqual(app.cells.count, 2)
    XCTAssertEqual(app.cells.buttons.firstMatch.label, "Savings\n\(currency)7620\(separator)00")
    XCTAssertEqual(app.cells.element(boundBy: 1).buttons.firstMatch.label, "Salary\n\(currency)5455\(separator)00")
  }
}

func localizedString(_ key: String) -> String {
  let result = NSLocalizedString(key, bundle: Bundle(for: AccountsViewUITest.self), comment: "")
  return result
}

后记

本篇主要讲述了单元测试和UI Test,感兴趣的给个赞或者关注~~~

你可能感兴趣的:(自动化Test使用详细解析(五) —— 单元测试和UI Test(二))