UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Using random values within Unit Tests, how do you feel about it?

Forums > Swift

I'm currently reading the Testing Swift book, and so far I haven't seen any mention in using random values within Unit Tests. I can see that doing so can (potentially) break the "R" (repeatable) of "FIRST", but at the same time I see so much value in doing such tests, e.g.:

struct Superhero {
      name: String

      func isFemale() -> String {
            return name.contains("woman")
      }
}
class ConverterTests: XCTestCase {
      func test_superheroIsNotFemale_whenItsNameDoesNotEndWithWoman() {
            let sut = Superhero(name: "\(RandomString)man"

            let isFemale = sut.isFemale()

            XCTAssertFalse(isFemale)
      }
}

Ok, now this is quite a silly example, but it helps illustrait my point. Clearly the implementation of isFemale has a bug, if we ever come across with a superhero named "Womaniterman", it will say he is a Female, but clearly he is not. Using random strings in the unit test this could eventually be detected (yes... probably not cause the chances to get the word "woman" out of a random string are super low, but you get my point).

So, how do you guys feel about using random values in unit tests? I know they can not be used in all situation, but should they be completelly forbbiden, or do you also see value in using them?

2      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.