Single global instance for multiple test cases in unit testing

424 Views Asked by At

I want to setup a global instance variable for all the test cases. Currently I could setup the variable for one test case but it is not set for the other. Mentioned below is my setup code.

func setupLightController()
{
    let btLight = HueBTLight(identifier: "093FB4B8-82E6-A124-3888-4F25C19CFDB7")
    btLight.name = "Hue Bloom"
    lightController = HueBTLightController(light: btLight)
    lightController.delegate += self
    bluetoothManager?.selectLight(lightController.light!)
    bluetoothManager?.delegate += lightController
}

Here, is the code for my first test case which runs perfectly fine.

func testColorModel()
{
    colorExpectation = self.expectation(description: "Testing setting color")

    setupLightController()
    wait(for: [colorExpectation], timeout: 20)
  
}

And here is my second test case

func testSetOn()
{
    lightExpectation = self.expectation(description: "Testing setting on and off")

    setupLightController()

    wait(for: [lightExpectation], timeout: 20)
}

How can I setup the lightController only once to be used in both the test cases. Also, I am using only one delegate callback for the expectation fulfill which works for only one expectation. Here is my delegate method

func didConnectLightController(_ object: CDHueBTLightController, success: Bool)
{
    self.connectionSuccess = success
    colorExpectation.fulfill()
    lightExpectation.fulfill()
}
1

There are 1 best solutions below

1
On

Implement your test case class's setUp() instance method to perform any setup that needs to be performed before every test method runs.