Exclude SwiftUI previews from code coverage?
Asked Answered
L

1

19

I'm having trouble getting my code coverage up to min. 90% because XCode takes the PreviewProvider into account.

What should I do? Remove all the SwiftUI previews? Or is there a way I can exclude some lines with 'PreviewProvider' keywords etc.

Xcode ver 12.0 Jenkins for CI slather & cobertura for code coverage

Side question, there is no official test suite available for unit testing SwiftUI components. Do you guys not test them at all, or use third party libraries? I've been using ViewInspector but i dislike that to track the updated state of the component, I need to include testing code in the actual codebase itself.

Lawsuit answered 30/10, 2020 at 7:25 Comment(3)
You can create dedicated test configuration with some defined macro and exclude preview provides by that define usage. SwiftUI as UI can be tested by same UI test target type as before for UIKit.Periclean
I'm not testing the SwiftUIView files, I just comment out the PreView.Campfire
Why do you want this? Are you really testing the view code? If not, you can simply exclude the view files instead. Otherwise, it seems what you need is a deceptive coverage.Lienlienhard
P
12

Here is a description of working approach (demo with Xcode 13 / iOS 15):

  1. Add explicit Testing (name as you want) configuration for UT

demo1

  1. Add conditional macro TESTING (name as you want) for Testing configuration

demo2

  1. Put preview provider into condition like
struct ContentView: View {
    var body: some View {
        Text("Hello, world!")
            .padding()
    }
}

#if !TESTING
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
#endif
  1. Set Testing configuration for UT schema

demo3

  1. Run UT and observe coverage

demo4

Periclean answered 3/9, 2021 at 5:9 Comment(1)
Does it work in Xcode 14 and iOS 16? In my case it does not work.Samal

© 2022 - 2024 — McMap. All rights reserved.