<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Chirag Kukreja on Medium]]></title>
        <description><![CDATA[Stories by Chirag Kukreja on Medium]]></description>
        <link>https://medium.com/@chiragkukreja_12635?source=rss-ee9c8677f0ca------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*yRQGHXkE6O8NtXne.</url>
            <title>Stories by Chirag Kukreja on Medium</title>
            <link>https://medium.com/@chiragkukreja_12635?source=rss-ee9c8677f0ca------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 12:06:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chiragkukreja_12635/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Best Practices of UITesting]]></title>
            <link>https://medium.com/@chiragkukreja_12635/best-practices-of-uitesting-99e64753ba8b?source=rss-ee9c8677f0ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/99e64753ba8b</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ui-testing]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Chirag Kukreja]]></dc:creator>
            <pubDate>Thu, 19 Mar 2020 09:44:30 GMT</pubDate>
            <atom:updated>2020-03-19T09:44:30.144Z</atom:updated>
            <content:encoded><![CDATA[<p>How can we make our tests easier to write, easier to understand and less prone to developer errors</p><p>so today we are gonna discuss 3 approaches :</p><ol><li>Using enums with UI tests</li><li>Using function builders for XCTAssert</li><li>BDD tests</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*06_MFNd6ULQSGlvIP3H2ZA.png" /></figure><p>consider this Screen which has 3 purposes:</p><ol><li>comparing 3 currencies to one base currency</li><li>Ability to change which currency to use as the base currency</li><li>Ability to enter the amount of money in currency exchange text field</li></ol><p>As we all know to search for existing UI elements on the XCUIApplication we use: XCUIElementQuery.</p><p>example to find static text Base Currency, we use</p><blockquote>XCUIApplication().textFields[“<strong>Base Currency</strong>”].exists</blockquote><p>so the initial test for this screen will look like as:</p><pre><strong>func</strong> testInitialState() {</pre><pre>XCTAssertTrue(app.staticTexts[“Base Currency”].exists)</pre><pre>XCTAssertTrue(app.staticTexts[“United States Dollar”].exists)</pre><pre>XCTAssertTrue(app.textFields[“1”].exists)</pre><pre>}</pre><p>here the initial value of textfield is 1.</p><p>As you can see, we have used hardcoded strings and if we want to access these elements in other tests, we have to look for those elements again and use hardcoded string again and these hard corded string are prone to developers errors. so we can capture these screen elements in the enum.</p><pre><strong>enum</strong> AppUI: String {</pre><pre><strong>case</strong> baseCurrencyView = &quot;Base Currency&quot;</pre><pre><strong>case</strong> unitedStatesDollarView = &quot;United States Dollar&quot;</pre><pre><strong>case</strong> euroView = &quot;Euro&quot;</pre><pre><strong>case</strong> canadianDollar = &quot;Canada Dollar&quot;</pre><pre><strong>case</strong> singaporeDollar = &quot;Singapore Dollar&quot;</pre><pre><strong>case</strong> initialTextField = &quot;1&quot;</pre><pre>}</pre><p>so here each case represents element on the screen and its raw value represents text on that screen.</p><p>Now can extend this enum to do element query</p><pre><strong>extension</strong> AppUI {</pre><pre><strong>var</strong> isStaticText: Bool {</pre><pre><strong>return</strong> XCUIApplication().staticTexts[<strong>self</strong>.rawValue].exists</pre><pre>}</pre><pre><strong>var</strong> isTextField: Bool {</pre><pre><strong>return</strong> XCUIApplication().textFields[<strong>self</strong>.rawValue].exists</pre><pre>}</pre><pre>}</pre><p>Now testing the initial state is great to start but when it comes to UI testing, it’s basically testing the functionality of the app and testing those users’ important interactions. so now we are going to change the base currency to euro and write the test for that to see whether that interaction is working or not</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qzDrUn0hMOLp14gSYuKD5w.png" /></figure><pre><strong>func</strong> testUpdatingBaseCurrencyCell() {</pre><pre>XCTAssertTrue(AppUI.unitedStatesDollarView.isStaticText)</pre><pre>XCTAssertFalse(AppUI.euroView.isStaticText)</pre><pre>app.tables.cells.element(boundBy: 2).tap()</pre><pre>XCTAssertTrue(AppUI.euroView.isStaticText)</pre><pre>}</pre><p>Here in this test, first, we check initial DollarView exists as the base currency and return false for euro view as euro view lies in the table view. Third lines indicate tapping on the 3rd cell of the table which is euro view and then we check euro view as static text.</p><p>But this test is not necessarily greatest yet because it’s understandable why we are checking our view as static text and tapping on the third line in the test is not clearly understand which view we are tapping. so let’s add some extension to AppUI</p><pre><strong>extension</strong> AppUI {</pre><pre><strong>var</strong> isWithinTableCell: Bool {</pre><pre><strong>return</strong> XCUIApplication().tables.cells.buttons[<strong>self</strong>.rawValue].exists</pre><pre>}</pre><pre><strong>var</strong> element: XCUIElement {</pre><pre><strong>if</strong> <strong>self</strong>.isStaticText {</pre><pre><strong>return</strong> XCUIApplication().staticTexts[<strong>self</strong>.rawValue]</pre><pre>} <strong>else</strong> <strong>if</strong> <strong>self</strong>.isTextField {</pre><pre><strong>return</strong> XCUIApplication().textFields[<strong>self</strong>.rawValue]</pre><pre>} <strong>else</strong> <strong>if</strong> <strong>self</strong>.isWithinTableCell {</pre><pre><strong>return</strong> XCUIApplication().tables.cells.buttons[<strong>self</strong>.rawValue]</pre><pre>}</pre><pre>fatalError()</pre><pre>}</pre><pre>}</pre><p>First property checks if that element lies within the table or not. The second one gives the element we want to interact with and for this, we will use our computed property to return that element we can interact with. and at the last, we return a fatal error because in this case, we are more concerned about these 3 elements.</p><p>now after doing the modification, our test looks like:</p><pre>XCTAssertTrue(AppUI.unitedStatesDollarView.isStaticText)</pre><pre>XCTAssertTrue(AppUI.euroView.isWithinTableCell)</pre><pre>AppUI.euroView.element.tap()</pre><pre>XCTAssertTrue(AppUI.euroView.isStaticText)</pre><pre>XCTAssertTrue(AppUI.unitedStatesDollarView.isWithinTableCell)</pre><p>Now, this is much more readable. Here First we check the euro view is in the table and after tapping the euro view, the united states dollar goes into the table view and the euro view becomes base currency.</p><p>We can further improve our AppUI enum by creating this new enum as we complex applications with multiple screens we have to implement those methods again and again.</p><pre><strong>enum</strong> ElementType {</pre><pre><strong>case</strong> textfield</pre><pre><strong>case</strong> statictext</pre><pre><strong>case</strong> tableCelltext</pre><pre><strong>init</strong>?(<strong>_</strong> text: String) {</pre><pre><strong>if</strong> XCUIApplication().textFields[text].exists {</pre><pre><strong>self</strong> = .textfield</pre><pre>} <strong>else</strong> <strong>if</strong> XCUIApplication().staticTexts[text].exists {</pre><pre><strong>self</strong> = .statictext</pre><pre>} <strong>else</strong> <strong>if</strong> XCUIApplication().tables.cells.staticTexts[text].exists {</pre><pre><strong>self</strong>  = .tableCelltext</pre><pre>} <strong>else</strong> {</pre><pre><strong>return</strong> <strong>nil</strong></pre><pre>}</pre><pre>}</pre><pre>}</pre><p>and to get element type, we will write like this:</p><pre><strong>extension</strong> ElementType {</pre><pre><strong>func</strong> getElement(with text: String) -&gt; XCUIElement {</pre><pre><strong>switch</strong>  <strong>self</strong> {</pre><pre><strong>case</strong> .statictext:</pre><pre><strong>return</strong> XCUIApplication().staticTexts[text]</pre><pre><strong>case</strong> .textfield:</pre><pre><strong>return</strong> XCUIApplication().textFields[text]</pre><pre><strong>case</strong> .tableCelltext:</pre><pre><strong>return</strong> XCUIApplication().tables.cells.staticTexts[text]</pre><pre>}</pre><pre>}</pre><pre>}</pre><p>Now we improved our element search query, now our AppUI can be made much simpler by writing these new properties:</p><pre><strong>extension</strong> AppUI {</pre><pre><strong>var</strong> type: ElementType {</pre><pre><strong>guard</strong> <strong>let</strong> type = ElementType(<strong>self</strong>.rawValue) <strong>else</strong> { fatalError() }</pre><pre><strong>return</strong> type</pre><pre>}</pre><pre>// After Modification</pre><pre><strong>var</strong> uiElement: XCUIElement {</pre><pre><strong>return</strong> type.getElement(with: <strong>self</strong>.rawValue)</pre><pre>}</pre><pre>}</pre><p>Now our already defined computed variable in AppUi can be modified to :</p><pre><strong>extension</strong> AppUI {</pre><pre><strong>var</strong> isStaticText: Bool {</pre><pre><strong>return</strong> type == .statictext</pre><pre>}</pre><pre><strong>var</strong> isTextField: Bool {</pre><pre><strong>return</strong> type == .textfield</pre><pre>}</pre><pre><strong>var</strong> isWithinTableCell: Bool {</pre><pre><strong>return</strong> type == .tableCelltext</pre><pre>}</pre><pre>}</pre><p>here we have to check just type, subtracting that logic out so that we don’t have to perform those queries on AppUI enum.</p><p>so till now, we have learned:</p><ol><li>Use the enum cases to represent different elements on one screen</li><li>Have a computed variable for the element in your enum that you can take action on</li><li>create a separate ElementType enum that can be reused for different enums you have for each screen</li></ol><p>So as we have seen previously writing the same assert statement, again and again, and it looks tedious. so what I like to do is simply call one method assertTrue() and that way each boolean in this statement is then being called on XCAssert but we don’t have to do actually ourself.</p><p>Before Function Builder:</p><pre><strong>func</strong> testInitialState() {</pre><pre>XCTAssertTrue(app.staticTexts[&quot;Base Currency&quot;].exists)</pre><pre>XCTAssertTrue(app.staticTexts[&quot;United States Dollar&quot;].exists)</pre><pre>XCTAssertTrue(app.textFields[&quot;1&quot;].exists)<br>}</pre><p>After function Builder:</p><pre><strong>func</strong> testInitialState() {</pre><pre>assertTrue {</pre><pre>AppUI.baseCurrencyView.isStaticText</pre><pre>AppUI.unitedStatesDollarView.isStaticText</pre><pre>AppUI.initialTextField.isTextField</pre><pre>}<br>}</pre><p>so we start creating boolean function builder and any function builder will be required to implement one method: buildBlock()</p><pre><strong>@_functionBuilder</strong></pre><pre><strong>class</strong> BooleanFunctionBuilder {</pre><pre><strong>static</strong> <strong>func</strong> buildBlock(<strong>_</strong> children: Bool...) -&gt; [Bool] {</pre><pre><strong>return</strong> children</pre><pre>}</pre><pre>}</pre><p>In this method, it takes any number of boolean statements and returns those array of booleans.</p><p>The power comes using this function builder as a parameter. Now in this assertTrue(), we will call builder on each of the booleans which we have put in the parameters and which will eventually call XCAssertTrue on all boolean statements.</p><pre><strong>func</strong> assertTrue(@BooleanFunctionBuilder builder: () -&gt; [Bool] ) {</pre><pre><strong>let</strong> expressions = builder()</pre><pre>expressions.forEach({XCTAssertTrue($0)})</pre><pre>}</pre><p>similarly, we can create the assertFalse() method.</p><pre><strong>func</strong> assertFalse(@BooleanFunctionBuilder builder: () -&gt; [Bool] ) {</pre><pre><strong>let</strong> expressions = builder()</pre><pre>expressions.forEach({XCTAssertFalse($0)})</pre><pre>}</pre><p>so function builders help make your code more readable and easier to write. They can be really really simple.</p><p>In BDD we write failing tests using “Given/When/Then” format and then we write step definitions or code to make our steps pass.</p><p>Now we need to write a class and a test name with given/when/then steps in a human-readable or in plain English.</p><pre><strong>class</strong> BDDTests: XCUITestingBase {</pre><pre><strong>func</strong> testTappingOnCurrencyInBDDStyle() {</pre><pre>givenAppIsReady()</pre><pre>whenITap(currency: .euroView)</pre><pre>thenIShouldSeeUpdatedBaseCurrency(currency: .euroView)</pre><pre>}</pre><pre>}</pre><p>You can see that steps are fairly readable, and you can imagine what they can do.</p><p>now let’s define those steps:</p><pre><strong>extension</strong> XCUITestingBase {</pre><pre><strong>func</strong> givenAppIsReady() {</pre><pre>assertTrue {</pre><pre>AppUI.baseCurrencyView.isStaticText</pre><pre>AppUI.unitedStatesDollarView.isStaticText</pre><pre>}</pre><pre>}</pre><pre><strong>func</strong> whenITap(currency: AppUI) {</pre><pre>currency.element.tap()</pre><pre>}</pre><pre><strong>func</strong> thenIShouldSeeUpdatedBaseCurrency(currency: AppUI) {</pre><pre>assertTrue {</pre><pre>AppUI.unitedStatesDollarView.isWithinTableCell</pre><pre>currency.isStaticText</pre><pre>}</pre><pre>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*je_BVVMzpWGoXvOIIXeraQ.png" /><figcaption>Test Report for BDD tests</figcaption></figure><p>Usually, UI Tests perform a lot of actions during execution e.g tapping buttons, swiping, etc. As of now, XCTest reports inside Xcode show all the actions in the test reports which is not particularly readable. Activities are the way to organize those actions into the group by giving meaningful names so the XCTest result will use that activity name in the result to make it more readable.</p><p>In order to make the Xcode report more readable, like in a BDD format, we can sprinkle the activity using: XCTContext.runActivity</p><pre><strong>extension</strong> XCUITestingBase {</pre><pre><strong>func</strong> givenAppIsReady() {</pre><pre>XCTContext.runActivity(named: &quot;Given App is ready &quot;) { <strong>_</strong> <strong>in</strong></pre><pre>assertTrue {</pre><pre>AppUI.baseCurrencyView.isStaticText</pre><pre>AppUI.unitedStatesDollarView.isStaticText</pre><pre>}</pre><pre>}</pre><pre>}</pre><pre><strong>func</strong> whenITap(currency: AppUI) {</pre><pre>XCTContext.runActivity(named: &quot;When I tap \(currency.rawValue) &quot;) { <strong>_</strong> <strong>in</strong></pre><pre>currency.element.tap()</pre><pre>}</pre><pre>}</pre><pre><strong>func</strong> thenIShouldSeeUpdatedBaseCurrency(currency: AppUI) {</pre><pre>XCTContext.runActivity(named: &quot;Then I should see updated base Currency as \(currency.rawValue)&quot;) { <strong>_</strong> <strong>in</strong></pre><pre>assertTrue {</pre><pre>AppUI.unitedStatesDollarView.isWithinTableCell</pre><pre>currency.isStaticText</pre><pre>}</pre><pre>}</pre><pre>}<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DnwEZLn0vNOFtkzc2D976g.png" /><figcaption>Test Report After Using Activities</figcaption></figure><p>Now you can see that the reports are much readable, our given/when/then steps are showing as a top-level. And then all the taps and everything is hidden under the activities. In this way, we can make our Xcode report much, much more readable.</p><p>Download sample project from <a href="https://github.com/chiragkukreja/XCUItesting">https://github.com/chiragkukreja/XCUItesting</a></p><p>References:</p><p><a href="https://testautomationu.applitools.com/introduction-to-ios-test-automation-with-xcuitest/">Introduction to iOS Test Automation with XCUITest by Shashikant Jagtap</a></p><p><a href="https://github.com/carson-katri/awesome-function-builders">Awesome Function Builders repo</a></p><p>Please feel free to share your opinion in the comments.</p><h3>If you liked this blog, hit the 👏 . Stay tuned for the next one!</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99e64753ba8b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Functional Programming]]></title>
            <link>https://medium.com/@chiragkukreja_12635/functional-programming-b4fb3d9963d?source=rss-ee9c8677f0ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4fb3d9963d</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Chirag Kukreja]]></dc:creator>
            <pubDate>Thu, 27 Feb 2020 19:24:38 GMT</pubDate>
            <atom:updated>2020-02-27T19:33:49.373Z</atom:updated>
            <content:encoded><![CDATA[<p>Implementing pseudo-keywords through Functional Programming</p><p>Consider the asynchronous code, which has a completion handler which mostly we use when we wait for the server response.</p><blockquote>func fetchData(_ completionHandler: @escaping (Data) -&gt; Void)</blockquote><p>so when we call this function, we write like</p><pre>fetchData { data in</pre><pre>  self.doSomething(with: data)</pre><pre> }</pre><p>since we are using self inside the closure, it will cause a retain cycle, so to avoid that we use weak self in the capture list.</p><pre>fetchData { [weak self] data in </pre><pre>  self?.doSomething(with: data) </pre><pre>}</pre><p>since here self is optional, and in some cases when we don’t want optional self, we use guard let to unwrap the self</p><pre>fetchData { [weak self] data in </pre><pre>   guard let self = self else { return } </pre><pre>   self.doSomething(with: data) <br>}</pre><blockquote>since this includes a lot of boilerplate code. So how can be do better…</blockquote><p>To solve this we can functional programming. As we all know functions are the first-class citizen in swift, which means</p><h4>Functions can be stored in variables</h4><pre>var increment: (Int) -&gt; Int = { $0 + 1 }</pre><h4>Functions can be passed as arguments</h4><pre>[1, 2, 3].map { $0 * $0 }</pre><h4>Functions can return functions</h4><pre>func buildIncrementor() -&gt; (Int) -&gt; Int {</pre><pre> return { $0 + 1 }</pre><pre> }</pre><p>so we can build functions that <em>enhance</em> the other functions. so let&#39;s see how it works</p><p>first, we will declare a protocol Weakifiable, which is only applicable for class, as only reference types can cause retain cycles.</p><h4>protocol Weakifiable: class { }</h4><p>now we will make every NSObject conform to this protocol using extension</p><h4>extension NSObject: Weakifiable { }</h4><pre>extension Weakifiable {</pre><pre>func weakify(_ code: @escaping (Self) -&gt; Void) -&gt; () -&gt; Void {</pre><pre>    return { [weak self] in</pre><pre>               guard let self = self else { return }</pre><pre>               code(self)</pre><pre>            }</pre><pre>       }</pre><pre>  }</pre><p>since completion handler is a function, here weakify also take one argument as a function which has one argument Self — the type that conforms to that protocol and return the function which takes no argument.</p><p>since this weakify function takes only one argument and if we want to send some data with this, we can make it generic like this</p><pre>func weakify&lt;T&gt;(_ code: @escaping (T, Self) -&gt; Void) -&gt; (T) -&gt; Void {</pre><pre>   return { [weak self] arg in</pre><pre>     guard let self = self else { return }</pre><pre>      code(arg, self)</pre><pre>   }</pre><pre>}</pre><p>now let&#39;s use this function now:</p><pre>fetchData( weakify { data, strongSelf in</pre><pre>  strongSelf.doSomething(with: data)</pre><pre>})</pre><p>so this code says, I want to weakify this closure and in the closure, I expect my data and strong instance of self. So by doing this lot of boilerplate code is removed.</p><h4>so here weakify is a function which enhances the piece of code, so we can call weakify a “pseudo-keyword”.</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4fb3d9963d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>