I'm trying to write UI test in Xcode to be able to know if my code causes UITableView to crash during refreshing on pull to refresh.
My test looks like this:
func testPullToRefresh_shouldNotCrash() throws {
do {
let app = XCUIApplication()
app.launch()
let tableView = app.tables.firstMatch
try pullToRefresh(from: tableView)
} catch {
XCTFail("Crashed")
}
}
Tried also doing:
func testPullToRefresh_shouldNotCrash() {
let app = XCUIApplication()
app.launch()
let tableView = app.tables.firstMatch
XCTAssertNoThrow(try pullToRefresh(from: tableView))
}
When I run test, app does crash, I see the exception in Xcode but after all test is succeeded
I tried writing sample project but it isn't working anyway
Sample code:
ViewController:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
private var dataSource = DataSource()
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = dataSource
tableView.delegate = dataSource
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(refreshData), for: .valueChanged)
tableView.refreshControl = refreshControl
}
@objc func refreshData() throws {
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
self.tableView.insertRows(at: [IndexPath(item: 0, section: 1)], with: .automatic)
self.tableView.refreshControl?.endRefreshing()
}
}
}
DataSource:
import UIKit
class DataSource: NSObject, UITableViewDataSource, UITableViewDelegate {
var data = ["Cell 1", "Cell 2", "Cell 3", "Cell 4", "Cell 5"]
// UITableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = data[indexPath.row]
return cell
}
// UITableViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
}
Test:
import XCTest
final class ExceptionTestsUITests: XCTestCase {
func testPullToRefresh_shouldNotCrash() throws {
do {
let app = XCUIApplication()
app.launch()
let tableView = app.tables.firstMatch
try pullToRefresh(from: tableView)
} catch {
XCTFail("Crashed")
}
}
func pullToRefresh(from element: XCUIElement) throws {
let startPosition = CGPoint(x: 100, y: 100)
let endPosition = CGPoint(x: 100, y: 500)
let start = element.coordinate(withNormalizedOffset: CGVector(dx: 0, dy: 0)).withOffset(CGVector(dx: startPosition.x, dy: startPosition.y))
let finish = element.coordinate(withNormalizedOffset: CGVector(dx: 0, dy: 0)).withOffset(CGVector(dx: endPosition.x, dy: endPosition.y))
start.press(forDuration: 0, thenDragTo: finish)
}
}
Is there any way to make it work?