Swift - Object instantiation in Test class

1.9k Views Asked by At

I am trying to test a class I have written. I have added a new test target and in there I have imported the target of the class I am trying to test. My code looks like this:

import XCTest
import TargetContainingClass

class Tests: XCTestCase
{
   var myClass = MyClass()

   // tests

}

However, I get the error:

'MyClass' is not constructible with '()'

MyClass does not contain an init() method so does not need to be constructed with anything. I therefore don't understand the error I am getting.

Any help here would be greatly appreciated.

Cheers

2

There are 2 best solutions below

13
On

You need to provide an implementation of init() as:

class MyClass {
  init () {}
}

The Swift documentation states:

“Swift provides a default initializer for any structure or base class that provides 
 default values for all of its properties and does not provide at least one initializer
 itself. The default initializer simply creates a new instance with all of 
 its properties set to their default values.”  
    Apple Inc. “The Swift Programming Language.”

But the above is apparently not true; in action:

  1> class MyClass1 {}
  2> MyClass1()
/var/folders/.../expr.DO8uJ4.swift:2:1: error: 'MyClass1' is not constructible with '()'
MyClass1()
^
  2> class MyClass { 
  3.     init () {} 
  4. }    
  5> MyClass()
$R0: __lldb_expr_3.MyClass = {}
0
On

I solved my issue firstly by providing an implementation of init() {} as suggested by @GoZoner, then to get rid of the Apple Mach-O Linker (id) Error I had to add the class I wanted to test as a Compile Source in the build phases.