Unit test private functions in a struct

Hi, newbie here,

If I have a non-pub fn in a struct, how do I write test that can access and test it?

const S = struct {
   fn add(a: i8, b: i8) i8 ...
};
test "test private fn in struct" {
   // how to access function `add` in S?
}

Hi @shaozi welcome to ziggit :slight_smile:

The function is accessible. pub is about the visibility when importing.
You can also include tests inside structs.

const std = @import("std");

const S = struct {
    fn add(a: i8, b: i8) i8 {
        return a + b;
    }
};

test "test private fn in struct" {
    try std.testing.expectEqual(2, S.add(1, 1));
}
> zig test filename.zig
All 1 tests passed.

Nice! Thank you.

Another question. When I run zig build test, how to list the tests that are run even when they passed?

See in the Build system tricks: Run your test suite exposed with std.testing.refAllDecls

To run tests from imported modules add the following code in the root source file:

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