Unit tests and "raw pointer"

I recently read chapter 12 of the book and decided to create my own implementation of the program, my program is a shell over the aho_corasick crate, which stores, updates and saves data from the search file in it. In my unit test for the AhoCorasickBuilder getter, I encountered a problem because AhoCorasickBuilder does not implement PartialEq. ChatGPT advised me to convert to "raw pointer"(*const _), whether it is correct to write such unit tests for the getter.:

#[test]
fn get_builder(){
    let mut builder=AhoCorasickBuilder::new();
    builder.auto_configure(&["some", "hay"]);
    let  grep = MiniGrep::new(["some", "hay"], "some haystack", None);
    assert_eq!(grep.get_builder() as *const _,&grep.corasick_builder as *const _);
}

or

#[test]
fn get_mut_matches(){
    let mut grep = MiniGrep::new(["some", "hay"], "some haystack", None);
assert_eq!(grep.get_mut_matches() as *const _,&mut grep.matches as *const _)
}

And how is it better to write like that?:

#[test]
fn get_matches(){
    let grep = MiniGrep::new(["some", "hay"], "some haystack", None);
    assert_eq!(&grep.matches,grep.get_matches())
}

or:

#[test]
fn get_matches(){
    let grep = MiniGrep::new(["some", "hay"], "some haystack", None);
    assert_eq!(grep.matches.as_slice() as *const _ ,grep.get_matches() as *const _)
}

You're just comparing the pointer values i.e. the memory addresses. That isn't going to do a meaningful equality test on the actual data inside the builder.

2 Likes

Well,yes,my goal was just to check that the getter returns a link to this field,but I would like to know if it makes sense to write such tests?

Ahh I see, no I don't think there's much value in that kind of a test. I'm sure there are some scenarios where ensuring a function returns a specific field might be important, but they'd be extremely niche. I would focus on writing tests for the parts of your code that are more closer to the higher level goals of your project

thank you

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.