Modern Concurrency in Swift by By Marin Todorov

Modern Concurrency in Swift by By Marin Todorov

Author:By Marin Todorov
Language: eng
Format: epub
Publisher: Ray Wenderlich


Adding a simple asynchronous test

A critical point to remember when adding asynchronous tests is to add the async keyword to each test method. Doing this lets you await your code under test and easily verify the output.

Add the following method to BlabberTests to create your first test:

func testModelSay() async throws { try await model.say("Hello!") }

Since the model is already configured to use the test-suitable URL session, you don’t need to do any additional setup — you just call say(_:) right away.

At this point, you’re ready to add your test expectations. First, you’ll verify that the last request the network performed, model.say("Hello!"), was sent to the correct URL.

Add the following code to do that:

let request = try XCTUnwrap(TestURLProtocol.lastRequest) XCTAssertEqual( request.url?.absoluteString, "http://localhost:8080/chat/say" )

You first unwrap the optional TestURLProtocol.lastRequest, then check that the URL matches the expected address: http://localhost:8080/chat/say.

Now that you’ve verified that the model sends the data to the correct endpoint, you can check that it also sends the correct data.

Finish up your test with the following piece of code:

let httpBody = try XCTUnwrap(request.httpBody) let message = try XCTUnwrap(try? JSONDecoder() .decode(Message.self, from: httpBody)) XCTAssertEqual(message.message, "Hello!")

You expect request.httpBody to decode as a Message. Once decoded, you assert that the message text equals “Hello!”, as expected.

If you wrote asynchronous tests prior to Swift 5.5, you’re likely excited about the brevity and clarity of this test code. And if you haven’t written asynchronous tests before, you really don’t need to know the lengths you had to go to set up a good asynchronous test back then!

To run the test, click Play in the editor gutter, to the left of func testModelSay()..., or press Command-U to run all tests.

Regardless of how you go about it, you’ll see the test pass and a green check mark (the best check mark!) will appear next to the test name in Xcode:



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.