clion swift XCTest resource file access?
I am trying to do what should be a simple test but I'm 110% stuck. Hopefully someone has done this before and can save me from my pit of frustration. I'm new to CLion so please be patient.
I have installed CLion and the swift extension. I have a project which includes tests. My Package.Swift includes a declaration asking for TestData files to be copied to the bundle:
import PackageDescription
let package = Package(
name: "asmtobin",
dependencies: [],
targets: [
.target(name: "asmtobin", dependencies: []),
.testTarget(name: "asmtobinTests", dependencies: ["asmtobin"],
resources: [.process("TestData")]
)
In my test project I have a TestData folder:
The CommentsOnly.txt file is what I am trying to access in a XCTest. There are quite a few examples around the Internet but for some reason I can't get anything to work. Any assistance is greatly appreciated. The following code fails:
func testBundleResources() throws {
let testBundle = Bundle(for: type(of: self))
let fooTxtPath = testBundle.path(forResource: "CommentsOnly", ofType: "txt")
let fooTxtURL = testBundle.url(forResource: "CommentsOnly", withExtension: "txt")
XCTAssertTrue(fooTxtURL != nil || fooTxtPath != nil)
}
Note: if I try and use Bundle.module.path(forResource, ofType) (like some of the Swift 5.3 examples say to) I get told that Bundle doesn't have a module member.
When I print some of the values the output is:
Testing started at 4:56 pm ...
/Applications/Xcode.app/Contents/Developer/usr/bin/xctest -XCTest asmtobinTests.asmtobinTests/testBundleResources /Users/ty/CLionProjects/asmtobin/.build/debug/asmtobinPackageTests.xctest
testBundle = Optional(Contents/Resources/ -- file:///Users/ty/CLionProjects/asmtobin/.build/x86_64-apple-macosx/debug/asmtobinPackageTests.xctest/)
fooTxtPath = nil
fooTxtURL = nil
XCTAssertTrue failed
/Users/ty/CLionProjects/asmtobin/Tests/asmtobinTests/asmtobinTests.swift:102: error: -[asmtobinTests.asmtobinTests testBundleResources] : XCTAssertTrue failed
Please sign in to leave a comment.
There seems to be a few problems. When I try to use Bundle.module.path(forResource, ofType) I get a compile warning saying:
I was just about to give up but I ran the code, ignoring the warning and surprisingly it worked. CLion seems to be reporting a problem incorrectly.
Unfortunately, this only works when the resource file isn't contained in a directory structure. So I can get my code working but it certainly seems like CLion needs some repairs to get testing working with Swift properly.
If I have this wrong please let me know so I can use CLion properly.
I just found that the Bundle.module not being recognised is a known issue and has been fixed for the 2021.1 release. I hope it also fixes the problem when the resource is contained in a directory.
The issue created by the user - https://youtrack.jetbrains.com/issue/CPP-24185