Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add additional func to apply coupon to cart #5

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions Basics/unit-testing.playground/Contents.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,24 @@ extension Product {
}
}

class ShoppingCart {
private var products: [Product] = []

var totalPrice: Double {
return products.reduce(0) { $0 + $1.price }
}

func add(_ product: Product) {
products.append(product)
}

func applyCoupon(_ coupon: Coupon) {
for i in 0..<products.count {
products[i].apply(coupon)
}
}
}

class ProductTests: XCTestCase {
func testApplyingCoupon() {
// Given
Expand Down Expand Up @@ -54,6 +72,22 @@ class ShoppingCartTests: XCTestCase {
// Then
XCTAssertEqual(shoppingCart.totalPrice, 35)
}

// Given, When, Then — which is commonly used in order to make tests easier to read and debug, especially when working within a team. It can sort of be read as ”Given these conditions, when these actions are performed, then this is the expected outcome

func testApplyingCoupon() {
var product1 = Product(name: "Book", price: 20)
var product2 = Product(name: "Movie", price: 15)
shoppingCart.add(product1)
shoppingCart.add(product2)

let coupon = Coupon(name: "Holiday Sale", discount: 20)
shoppingCart.applyCoupon(coupon)

XCTAssertEqual(product1.price, 16)
XCTAssertEqual(product2.price, 12)
XCTAssertEqual(shoppingCart.totalPrice, 28)
}
}

// --- Running all of our unit tests within the playground ---
Expand Down
2 changes: 1 addition & 1 deletion Basics/unit-testing.playground/contents.xcplayground
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<playground version='5.0' target-platform='ios' executeOnSourceChanges='false'>
<playground version='5.0' target-platform='ios'>
<timeline fileName='timeline.xctimeline'/>
</playground>