Swift mutation testing: do your boundary assertions work?
You finish changing business logic on Windows, send the code to a cloud Mac, and watch every test pass. Yet the code still says “a perfect score cannot be submitted” when it should say “a perfect score can be submitted.” Coverage only tells you that a line ran; it does not prove your assertions will catch an incorrect condition. Mutation testing reverses the process: deliberately introduce a small defect, then see whether the existing tests detect it.
Below, we will validate a score range in a standalone Swift package, without connecting to a network, touching signing materials, or modifying the main project. You can run everything in the terminal of a remote desktop session. At the end, you will have the original source, logs for each experiment, and structured results.
Define what counts as a valid detection
The business contract is simple: integer scores from 60 through 100 are accepted. Choose two mutations with clear behavioral differences: change the lower-bound comparison from >= to >, and expand the upper bound from 100 to 101.
A test with an input of 60 should catch the first defect; a test with an input of 101 should catch the second. Test only 80, and both defects slip through. Even full function coverage cannot change that.
A mutant that fails to compile is not a defect detected by the tests. First confirm that the build succeeds, then confirm that the failure comes from the intended assertion—not from the toolchain, permissions, or an abnormal test-process failure.
The experiment must start with a fully passing baseline. If the baseline fails, stop immediately. Do not attribute a pre-existing failure to a mutation.
Create an experimental package outside the main repository
Your terminal must be able to run swift, and the batch script also requires Python 3. First run swift --version and python3 --version to record the actual toolchain versions. There is no need to require a particular, unverified version.
LAB="$(mktemp -d "${TMPDIR%/}/mutation-lab.XXXXXX")"
cd "$LAB"
swift package init --type library --name ThresholdGate
cat > Sources/ThresholdGate/ThresholdGate.swift <<'SWIFT'
public func accepts(_ score: Int) -> Bool {
score >= 60 && score <= 100
}
SWIFT
cat > Tests/ThresholdGateTests/ThresholdGateTests.swift <<'SWIFT'
import XCTest
@testable import ThresholdGate
final class ThresholdGateTests: XCTestCase {
func testBoundaryContract() {
XCTAssertFalse(accepts(59))
XCTAssertTrue(accepts(60))
XCTAssertTrue(accepts(100))
XCTAssertFalse(accepts(101))
}
}
SWIFT
swift test
The four assertions cover a value outside the range, the lower bound, the upper bound, and another value outside the range. The sample test file generated by the package initialization command has been replaced entirely, so template tests will not be mistaken for meaningful coverage.
This is a pure-logic experiment running on macOS. After moving the code into an iOS project, run it again through that project's test target. Logic that involves platform frameworks cannot be considered accepted solely because this experiment passes.
Make one change at a time and keep separate logs
Save the following as mutate.py in the experiment directory, then run python3 mutate.py. The script generates each mutation from the original source rather than stacking changes on top of the previous defect.
import json
import pathlib
import subprocess
import sys
root = pathlib.Path.cwd()
source = root / "Sources/ThresholdGate/ThresholdGate.swift"
original = source.read_bytes()
text = original.decode("utf-8")
logs = root / "mutation-logs"
logs.mkdir(exist_ok=True)
def run(args, name):
with (logs / name).open("wb") as output:
return subprocess.run(
args,
cwd=root,
stdout=output,
stderr=subprocess.STDOUT
).returncode
if run(["swift", "test"], "baseline.log") != 0:
sys.exit("Baseline failed; inspect mutation-logs/baseline.log")
mutations = [
("lower-exclusive", "score >= 60", "score > 60"),
("upper-expanded", "score <= 100", "score <= 101")
]
results = []
try:
for name, before, after in mutations:
if text.count(before) != 1:
raise RuntimeError("Mutation target is not unique")
try:
source.write_text(text.replace(before, after), encoding="utf-8")
build = run(
["swift", "build", "--build-tests"],
name + ".build.log"
)
if build != 0:
status = "build_failed"
else:
test = run(
["swift", "test", "--skip-build"],
name + ".test.log"
)
status = "survived" if test == 0 else "test_failed"
results.append({"mutation": name, "status": status})
finally:
source.write_bytes(original)
finally:
source.write_bytes(original)
(logs / "results.json").write_text(
json.dumps(results, indent=2) + "\n",
encoding="utf-8"
)
sys.exit(0 if all(
item["status"] == "test_failed" for item in results
) else 1)
Building and running are separate steps so that syntax errors do not get counted as defects detected by tests. For every mutation, the tests are rebuilt and the newly generated test binary is run. Do not skip the build step and repeatedly run stale artifacts.
The source is restored through finally, but that offers no protection if the process is forcibly terminated or the machine shuts down unexpectedly. Run this only in an isolated copy. Production automation must also retain a clean input that can be checked out again.
Review the failure evidence, then run a reverse experiment
Open mutation-logs/results.json. Normally, both entries should be test_failed. Then inspect the corresponding test logs individually: the lower-bound mutation should fail the assertion for 60, and the upper-bound mutation should fail the assertion for 101.
The script's test_failed status is only a classification awaiting review; it does not automatically mean “mutant killed.” Failure to start the tests, an abnormal exit, and an assertion failure can all produce a nonzero exit code. Count a valid detection only when the log proves that the expected assertion failed.
Next, temporarily remove the assertion for input 60, leave the other three in place, and rerun the script. The lower-bound mutation should become survived, and the script should return a nonzero exit code. This verifies that the experiment can actually expose a weakness in the tests rather than reporting success regardless of the circumstances. Restore the assertion afterward.
What to do with surviving mutants
First check whether the mutation actually changes business behavior, then check whether the intended test ran. Do not add assertions that verify only implementation details just to improve the numbers. If the two versions of the code are fully equivalent under the contract, document why the mutation is excluded instead of forcing a failure.
Turn this into a small, explainable checklist
When bringing this approach into everyday development, start with error-prone comparison operators, empty-collection branches, and early-return conditions. Select only a few business-critical locations at a time. Text replacement is suitable only for unique snippets like those in this experiment. Real projects should use tools that can target syntax nodes, avoiding accidental changes to strings or other functions.
For acceptance, check that the baseline is fully green, each mutant was built separately, each failed assertion corresponds to a counterexample to the business rule, the source was restored, and swift test passed again after restoration. Keep the commit identifier, toolchain versions, mutation definitions, and logs so the results can be reviewed later.
Do not deliver only a detection percentage. List mutations with confirmed detections, surviving mutants, compilation failures, and equivalent mutants excluded from the results. That is how you determine whether to improve the tests or fix the experiment. For an independent developer, proving that two critical boundaries are genuinely guarded is more valuable than running a large number of mutations whose results cannot be explained.
Frequently asked questions
Does a compilation failure count as a detected mutation?
No. The mutated code never reached test execution. Record it separately; a useful detection requires a successful build followed by the expected assertion failure.
Should every mutation make the tests fail?
First exclude equivalent mutations and verify that the intended tests ran. If a mutation changes required behavior but still passes, add a counterexample that distinguishes it from the correct implementation.
Get your own cloud Mac
A dedicated physical machine, not a virtual machine. Rent by the day, with same-day activation. Sign in to open the remote desktop in your browser. If you need help, submit a support ticket in the console.
Get a cloud Mac