Testable code shared between C# and Swift

We developed an idiom for writing tests in Swift which can be pasted into C# for running. It needs one search-and-replace, but that’s it. If you’re wondering “why?” you’re probably not a programmer. The need was to be able to establish that a Windows app written in C# does exactly the same thing as an iOS app written in Swift. That way we can guarantee compatibility and inter-operability of a hybrid system working across the two platforms.

For the programmer-folks in the audience, here’s some code:

    func testShowToLeadUnderwriterSuccess() {
        beBroker();
        var contract = makeContract( Status.NotFinalised, 
            makeBuyer().channel, makeBroker().channel );
        var opResult = contract.showToLeadUnderwriter( makeUnderwriter() );
        XCTAssertTrue( opResult.result );
        XCTAssertEqual( 3, count(contract.channels) );
        XCTAssertEqual( toString(Status.QuotationRequest), contract.status );
    }

We pick up the test functions from Swift and paste them into a suitable class in C#. We then search for fund and replace it with [TestMethod] public void and we’re done. Back into the red-green-refactor TDD cycle.

Our recommendations are:

  • use semi-colons in Swift
  • use var instead of let, and ignore the Swift complaints
  • write lots of functions in the base class, like beBroker() and makeContract() above
  • tell Swift not to require named arguments for the test functions
  • implement equivalent XCTAssert functions in C#
  • use parameter list functions: Swift’s string… and C#’s params string[]
  • be patient with the compile and run time in Swift – it will get there in the end