Integrate Combine Into an App

Aug 5 2021 · Swift 5.4, macOS 11.3, Xcode 12.5

Part 2: Integrate with Core Data & Unit Test

09. Test with Given-When-Then

Episode complete

Play next episode

Next
About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 08. Use @FetchRequest to Get Core Data Entries Next episode: Part 2 Quiz: Integrate Combine into an App

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Testing is an important part of development for all apps. You can even write tests against your Combine code. You’ll use a pattern to organize your test logic - the Given-When-Then pattern.

func test_backgroundColorFor50TranslationPercentIsGreen() {
	// Given
	let viewModel = self.viewModel()
	let translationPercent = 0.5
	let expected = Color("Green")
	var result: Color = .clear
	
After that, subscribe to the `$backgroundColor` publisher, using a `sink` to capture the value, and store the subscription.
	viewModel.$backgroundColor
	  .sink(receiveValue: {
	    result = $0
	  })
	  .store(in: &subscriptions)
	// When
	viewModel.updateBackgroundColorForTranslation(translationPercent)
	// Then
	XCTAssert(result == expected, "Color expected to be \(expected) but was \(result)")
}
func test_fetchJokeSucceeds() {
  // Given
  let viewModel = self.viewModel()
  let expectation = self.expectation(description: #function)
  let expected = self.testJoke.value
  var result: Joke!
  viewModel.$joke
    .dropFirst()
    .sink(receiveValue: {
      result = $0
      expectation.fulfill()
    })
    .store(in: &subscriptions)
  // When
  viewModel.fetchJoke()
  // Then
  waitForExpectations(timeout: 1, handler: nil)
  XCTAssert(result == expected, "Joke expected to be \(expected) but was \(String(describing: result))")
}