Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create an init method for a struct which is only visible in tests?

I want to create an init method for my struct with a bunch of default values for use in unit tests. I don't want the main module to be able to see this init method.

I thought I could simply create an extension of my struct in my test class's file, but this doesn't work:

Foo.swift (in app target):

public struct Foo {

    public let bar: Int

    public init(colour: String) {
        self.bar = colour == "Green" ? 0 : 1
    }

}

FooExtension.swift (in test target):

extension Foo {

    public init(bar: Int = 42) {
        self.bar = bar
    }

}

Note the non-default initializer in the main file, so the Swift compiler does not automatically create the memberwise initializer for me. Maybe this has something to do with the problem, maybe not.

The Swift compiler complains Cannot assign to 'bar' in 'self'. But when I copy that init method into the original definition of my Foo struct in my main target, it works fine. I get the same results with or without the default parameter values.

Is this a Swift compiler bug or something to do with defining extensions in one module for structs defined in another? Everything works fine when I try and replicate this in a Playground.

I am using Swift 1.2 with Xcode Version 6.4 (6E35b)

like image 268
Robert Atkins Avatar asked Feb 18 '15 10:02

Robert Atkins


People also ask

Can we write test cases for private methods?

To test private methods, you just need to test the public methods that call them. Call your public method and make assertions about the result or the state of the object. If the tests pass, you know your private methods are working correctly.

Can we test protected methods?

To test a protected method using junit and mockito, in the test class (the class used to test the method), create a “child class” that extends the protagonist class and merely overrides the protagonist method to make it public so as to give access to the method to the test class, and then write tests against this child ...

Does struct have init Swift?

In Swift, all structs come with a default initializer. This is called the memberwise initializer. A memberwise initializer assigns each property in the structure to self. This means you do not need to write an implementation for an initializer in your structure.


1 Answers

I've had a response to the radar I filed on this; what I'm asking for is now explicitly disallowed.

like image 176
Robert Atkins Avatar answered Sep 19 '22 21:09

Robert Atkins