Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.4k views
in Technique[技术] by (71.8m points)

swiftui - How to unit test an @ViewBuilder function?

An example function:

@ViewBuilder func returnView() -> some View {
        if thisIsTrue == true {
            SomeView()
        } else {
            AnotherView()
        }
    }

I've tried testing like this:

let testView = sut.returnView()
XCTAssert(testView is SomeView)

Which passes when there is only one possible type of view, but then fails as soon as there is a choice.

Any suggestions as to how I can unit test the output of this function?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The opaque return type some View means this function always returns exactly one type on all paths our of the function and that type conforms to View, so while it looks like you are returning two different things the ViewBuilder in fact collapses this into a single type that is generic with respect to the real return type. If you want to know what the opaque type really is you can just have the compiler tell you. For instance here is a playground. Note that this solution is fragile because changing the implementation of the function very likely will change the return type.

import SwiftUI

struct SomeView: View {
  var body: some View { EmptyView() }
}

struct AnotherView: View {
  var body: some View { Color.red}
}

@ViewBuilder func returnView() -> some View {
  if true {
    SomeView()
  } else {
    AnotherView()
  }
}

let a = returnView()

print(type(of: a))

output:

_ConditionalContent<SomeView, AnotherView>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...