ziglang / zig

General-purpose programming language and toolchain for maintaining robust, optimal, and reusable software.
https://ziglang.org
MIT License
34.51k stars 2.52k forks source link

Make private const/vars/function visible for testing #2852

Open DrDeano opened 5 years ago

DrDeano commented 5 years ago

When running under zig test.
When separating out the unit tests from the main source file, have the private const/vars/function visible for the testing file that is testing the source file. For example:

src.zig:

const some_value: u32 = undefined;

pub fn init() void {
    some_value = 100;
}

test_src.zig:

const src = @import("src.zig");
const expectEqual = @import("std").testing.expectEqual;

test "some_value set after init()" {
    src.init();
    expectEqual(100, src.some_value);
}
ghost commented 5 years ago

You could also argue for only allowing public members to be visible inside tests, because if you test private members, you might end up testing implementation instead of testing behavior, and that's bad if you later want to refactor or switch to a new implementation.

The most important thing is consistency though, no matter which file the test resides in.

See: https://teamgaslight.com/blog/testing-behavior-vs-testing-implementation

https://softwareengineering.stackexchange.com/questions/274937/is-it-bad-practice-to-make-methods-public-solely-for-the-sake-of-unit-testing

PavelVozenilek commented 5 years ago

I'd proposed this once in #608. Ability to test the internals is very useful, if one is into defensive coding.