#Test Private Fields in Separate Test File

25 messages · Page 1 of 1 (latest)

tight lake
#

Is there a way to test your private fields with an external test file?

I would like to have my tests in their own file to keep my files smaller and more digestible. I found this answer, but I am getting the error: unresolved module, can't find module file.

gleaming crane
tight lake
gleaming crane
#

Specifically, they go in a submodule of the thing being tested

#

Tests inside tests rather than src are considered integration test, and behave as if they were separate crates

tight lake
#

Ah I see. So no way to keep the tests in tests/ if it isn't an public field. Thanks fof the help.

#

Do you recommend just keeping it in one file or creating a file called lib_test.rs in src/ or something to that effect?

proper bramble
#

If it's only a few tests (less than 10) then keeping it in the same file is usually how it's done. Otherwise, just do mod tests; and make a tests.rs file.

tight lake
supple lodge
#

Alternatively, you can use pub(crate)

gleaming crane
supple lodge
gleaming crane
supple lodge
#

Right, did not notice

#

Hmm, how about the cfg macro. It is pretty dirty but can generate two versions of the struct one with public fields

robust mango
#

cfg for enabling access for testing is not a really nice solution because there's no way to instruct Cargo "enable this feature if testing"

#

the closest you can get is required-features which lets you write a test that runs only if the feature is enabled, and then you have to always cargo test --feature=test_stuff or cargo test --all-features to get full test coverage

#

(though arguably you should test with features anyway … but it's extra work if you don't have any features that aren't for testing)

supple lodge
#

have that use the feature that gets you the same structs with public fields

robust mango
#

that could work but then to get proper test coverage you need to build excluding that crate sometimes

supple lodge
#

I'm not saying it is a good solution, but it is a solution

low jasper
#

If you want to test private fields, just do it from a module under the module where the struct is