Initialize object once for all test cases

37 views Asked by At

In the following bit of code appSettings variable initializes for every test case. How to make it initialize once for the whole test class? Using singleton would be a problem if it is used for several test classes when you run them together at once, because it will be initialized once for all test classes

final class TestsmthTests: XCTestCase {
        
        var appSettings = AppSettings()
    
        override func setUpWithError() throws {
    
        }
    
        func testExample() throws {
            
        }
        
        func testMore() throws {
            
        }
    }
1

There are 1 answers

0
JeremyP On

Make it a static variable of your XCTestCase class.

final class TestsmthTests: XCTestCase {
        
        static var appSettings = AppSettings()
    
        override func setUpWithError() throws {
    
        }
    
        func testExample() throws {

            var foo = TestsmthTests.appSettings.someProperty()  
        }
        
        func testMore() throws {
            var foo = TestsmthTests.appSettings.someProperty()              
        }
    }

I'd be reluctant to do this though because, the tests are meant to be independent and so, if you modify appSettings in a test, you may start seeing issues.