Skip to content

Instantly share code, notes, and snippets.

@ricardopereira
Created September 13, 2021 17:17
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ricardopereira/7f8c352b5322b0f67053830367029110 to your computer and use it in GitHub Desktop.
Save ricardopereira/7f8c352b5322b0f67053830367029110 to your computer and use it in GitHub Desktop.
Using the SKTestSession in XCTest.
import XCTest
import StoreKitTest
@available(iOS 14.0, *)
class SubscriptionTests: XCTestCase {
private var session: SKTestSession!
private var subscriptionsController: SubscriptionsController!
override func setUpWithError() throws {
session = try SKTestSession(configurationFileNamed: "SKFooConfiguration")
session.disableDialogs = true
session.clearTransactions()
subscriptionsController = SubscriptionsController()
}
func testIfThereIsNoUnexpectedSubscriptionProduct() {
let productsExpectation = XCTestExpectation(description: "products")
subscriptionsController.onProductsDidLoad = {
productsExpectation.fulfill()
}
subscriptionsController.onProductsLoadingDidFailed = { error in
XCTFail("Should not reach this block")
}
subscriptionsController.loadProducts()
wait(for: [productsExpectation], timeout: 5.0)
XCTAssertEqual(subscriptionsController.products.count, 2)
XCTAssertTrue(subscriptionsController.products.contains(where: { $0.productIdentifier == "foo.iap.monthly" }))
XCTAssertTrue(subscriptionsController.products.contains(where: { $0.productIdentifier == "foo.iap.annually" }))
}
func testPurchasingProductShouldSucceed() throws {
let productsExpectation = XCTestExpectation(description: "products")
subscriptionsController.onProductsDidLoad = {
productsExpectation.fulfill()
}
subscriptionsController.loadProducts()
wait(for: [productsExpectation], timeout: 5.0)
XCTAssertEqual(subscriptionsController.products.count, 2)
let product = try XCTUnwrap(subscriptionsController.products.first)
let purchaseProductExpectation = XCTestExpectation(description: "purchase product")
subscriptionsController.startPurchase(of: product) { error in
XCTAssertNil(error)
purchaseProductExpectation.fulfill()
}
wait(for: [purchaseProductExpectation], timeout: 5.0)
let transaction = try XCTUnwrap(subscriptionsController.purchasesStore.getLatestPurchaseTransaction())
XCTAssertEqual(transaction.productIdentifier, product.productIdentifier)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment