Unit test with external module

I have a test that needs to reference an external module, but I keep getting this error whenever I run zig test on the file that has my test:

src/game/resourceManager.zig:3:22: error: no module named 'core' available within module test
const core = @import("core");

The problem is zig test doesn’t use build.zig, so it doesn’t know anything about my modules, right? So how do I run my test? Do I have to set up all my tests in build.zig and then run ALL my tests with zig build test? Is there a way to run the tests in a single file and also reference modules?

Still, I’m not even sure my tests are actually running with zig build test. I get no output, even though I added the file with my tests to build.zig, like this:

 const exe_tests = b.addTest(.{ .root_source_file = .{ .path = "src/main.zig" }, .target = target, .optimize = mode });
    const exe_tests2 = b.addTest(.{ .root_source_file = .{ .path = "src/game/resourceManager.zig" }, .target = target, .optimize = mode });
    exe_tests.root_module.addImport("core", core_module);
    exe_tests.root_module.addImport("game", src_module);
    exe_tests2.root_module.addImport("core", core_module);
    exe_tests2.root_module.addImport("game", src_module); // probably not necessary
    
    const test_step = b.step("test", "Run unit tests");
    test_step.dependOn(&exe_tests.step);
    test_step.dependOn(&exe_tests2.step);

Is there a way to add all my unit tests automatically without having to use Builder.addTest() on every single file with a test? Maybe that’s what the const exe_tests = b.addTest(.{ .root_source_file = .{ .path = "src/main.zig" }, .target = target, .optimize = mode }); line is meant to do, but that assumes (maybe?) the code I want to test has already been integrated into the rest of my code.

Is there any documentation for testing that goes beyond “just run zig test [filename]”? If you can’t tell I’m completely lost.

Your module and test setup looks correct for zig build test. It must be a reference problem.


There is a way to specify modules in the zig test command line using the --dep and -M flags.
But it is better to use the builder to produce this command line using zig build test.


Inside your src/main.zig you must reference all declarations so that the zig compiler includes them in the test compilation.
You can reference all the declarations in a module using std.testing.refAllDecls or std.testing.refAllDeclsRecursive

test {
    std.testing.refAllDecls(@This());
}

see: 4) Run your test suite exposed with std.testing.refAllDecls

Run your tests using: zig build test --summary all or new

  --summary [mode]             Control the printing of the build summary
    all                        Print the build summary in its entirety
    new                        Omit cached steps
    failures                   (Default) Only print failed steps
    none                       Do not print the build summary
2 Likes