How to write unit test for button tap?

swift unit test view controller
swift ui test tap button
unit testing network code ios
ios ui testing
advanced unit testing swift
xcode ui testing accessibility
xctest buttons
swift testing framework

Here I'm trying to check unit test cases for view controller. - I have a view controller with button and label. - When you click on the button, it will call another method. which feeds the data to the button action label text change. - I want to check that button triggered that method or not? without adding any boolean or return type of the function.

Here is my code.

class ViewController: UIViewController {

    @IBOutlet weak var buttonFetch: UIButton?

    @IBOutlet weak var nameLabel: UILabel!

    override func viewDidLoad() {


    @IBAction func fetchUser() {
        self.nameLabel.text = self.getUser()

    func getUser() ->String {

struct User  {
    static func data()->String{
        return "Apple"

Here is my test case

func testFetchUserAction() {
        controller.buttonFetch?.sendActions(for: .touchDown)
        // I want to test the method getUser from viewcontroller gets called or not
        // some thing like this XCTAssert(self.controller.getUser(),"not called")
        XCTAssertEqual(self.controller.nameLabel.text!, "Apple")


What you're missing:

Make sure to call loadViewIfNeeded() somewhere.

This can be in the test, or in setUp(). This will load your outlets, and call viewDidLoad().

Then, as much as possible, test the result of invoking an action, instead of whether or not a method was called. You've done this in your example assertion.

I'd also add that the correct action for buttons is almost always .touchUpInside, not .touchDown. This allows the user to press a button, then drag away to change their mind. "I don't want to push this after all."

How to write unit test for button tap?, that invoking the action method produces the desired result. I am trying to write a unit test case for my Login Form, in this if Username and Password empty then we click login button it will show alert, i want to write testcases for this scenario, for me button action not working and alert not showing with unit testing , i am searching for solution long time any one could help..Thanks!

Found something similar on another response, attempted something like this? Source: How to add tap action for button in "Unit Testing" and show Alert

func testTappingLoginButton_ShouldPresentAlert() {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let sut = storyboard.instantiateInitialViewController() as! ViewController
    let alertVerifier = QCOMockAlertVerifier()

    sut.loginButton.sendActions(for: .touchUpInside)

    XCTAssertEqual(alertVerifier.presentedCount, 1)

Let me know if it works or not!

How to unit test button taps on a view controller with XCTest , What you're missing: Make sure to call loadViewIfNeeded() somewhere. This can be in the test, or in setUp() . This will load your outlets, and  Thanks for reading, feel free to share and tap on clap button, if you find it useful and please add comments if you need any further help in setting up TypeScript test cases or if I missed

I have tried like below, its passed the test. But I'm not sure it is correct or not?

XCTAssertNotNil(self.controller!.getUser, "get user method not called")

[PDF] iOS Unit Testing by Example, We also need to be able to verify that our view controller behaves the way it should when the user interacts with it. Today we'll test taps on the login button to make  Open the BullsEye project and press Command-6 to open the Test navigator. Click the + button in the lower-left corner, then select New Unit Test Target… from the menu: Accept the default name, BullsEyeTests. When the test bundle appears in the Test navigator, click to open the bundle in the editor.

Have you tried as like below..

func testFetchUserAction() {

    self.controller.nameLabel.text = nil

    //Use this line, If you assigned touchUpInside to your button action
    controller.buttonFetch?.sendActions(for: .touchUpInside)

    //Use this line, If you assigned touchDown to your button action
    controller.buttonFetch?.sendActions(for: .touchDown)

    XCTAssert(self.controller.nameLabel.text != nil, "not called")


Note: To make test case failed purposely, you can change UIControl.Event in sendActions

iOS Unit Testing and UI Testing Tutorial, Tapping a button is one of the most basic things users do with controls. If we can write unit tests for button taps, werll open up an entire world for  Unit testing is a great discipline which can lead to 40%-80% reductions in production bug density. Unit testing also has several other important benefits: But some things are easier to unit test

User interface testing with XCTest, When we created our project we added both unit tests (Project39Tests.swift) and also UI click the search button, then use the on-screen keyboard to type "test". Enter automated UI tests. I really like to use the Xamarin UI Test Recorder to get the inital scaffolding of a UI test built and then tweak it from there. Using the recorder, you simply tap/type/swipe around the app and use it like you normally would, and the test recorder translates that into Xamarin.UITest commands that make up your automated

How to test your user interface using Xcode – Hacking with Swift, Where possible regular unit tests are preferable. UI testing is notoriously flaky, and ideally you should make most of your app Go ahead and press that button now, and you should see Xcode build and launch your app. Create your First Unit Test(Step by Step) Once you have done with your API development you can create your Developer test cases to verify your code. I am using Visual Studio 2010 Ultimate version. So don't know whether below option appear for you or not. But you can Use Microsoft.VisualStudio.QualityTools.UnitTestFramework namespace for

XCTest. Test if UIButton is Connected And Has Action, In this XCTest tutorial, you will learn how to write a unit test that will test if UIButton is connected to @IBOutlet and has @IBAction assigned. Open the Coded UI Test Builder dialog by placing the cursor in the CodedUITestMethod1 method and then choosing Test > Generate Code for Coded UI Test > Use Coded UI Test Builder. Add the controls to the UI control map. Use the Coded UI Test Builder cross-hair tool to select the button control in the UWP app.

  • Why you do not use XCUITest for ui testing like button is clicked or not ?
  • @JatinKathrotiya Unit tests are much faster than UI tests.
  • Then your goals are self contradictory. Unit tests test business logic. If you want to test that tapping a button has a certain effect, that’s an UI test.
  • @matt Unit test test whatever you want them to. Don't limit yourself. I live on unit testing view controllers.
  • Worthwhile argument for sure.
  • Don't post updates to your question as an answer to you question. And please read how to ask good questions.