Unable to test object

What I’m trying to do

pub const Arr = struct { a: std.BoundedArray(i32, 8),};

test “Array” {
     const s = “array”;
     const b = Arr {.a = s};
     try expect(b.arr.len == 2);
}

Log :

Build Summary 1/1 steps succeeded

You have not told us what you are trying to do, you have not told us is happening or should happen.
Code snippets with no context don’t provide any of that.
Speaking of, use ``` above and below code to make code snippets.

fn main() void {
    // like this
}

I am just going to go over everything wrong with what you’ve given me.

Your test code is wrong, Arr has no field named a, instead it has a buffer and a len field. The reason it built successfully is that tests aren’t included outside test builds.

In a project with a build.zig there should be a test step you invoke by running zig build test.
If it’s a single file program, you can just zig test path/to/file

You should not initialise the struct yourself, instead use the default initialisation (which should be changed to an empty decl, assuming you are using zig 0.14). Then use the provided functions to modify the contents.

String literals are pointers to a utf-8 encoded array, meaning they are arrays of u8 not i32, so you can’t just assign them to the inner buffer. They’d need to have the same element type and length and be dereferenced to do that.
You can use appendSlice or its AssumeCapacity variant to do that. (they still need the same element type)

Lastly, to get the length, do b.len.

1 Like

I’m testing the code to see what happens as errors but I get “succeeded”.

Assuming the command output you posted is what you are referring to.
You are just building, the build succeeded.
If you were testing the build would fail since your test has invalid code.

1 Like

What commands are you using to run the tests? I’m surprised if the tests built, because Arr is a struct with one member a, so this should fail to compile

You can run tests on a single file by running zig test path/to/file.zig. If you are using build.zig, running zig build test would be what you are looking for.

Zig will not compile your tests unless they are referenced due to lazy compilation. If you are only running zig build it will not reference your tests at all and therefore not compile nor run them.

4 Likes