You can use cfg!(test)
:
if cfg!(test) {
// do test stuff
} else {
// do non-test stuff
}
However, this can lead to fragile code. For example, you might accidentally not execute some code in production, even though the tests all pass. It is often more robust to switch code at the item level, which would result in a compile error if you get it wrong:
#[cfg(test)]
impl Write for DB {
fn write(&mut self, buf: &[u8]) -> Result<usize> {
// test stuff
}
fn flush(&mut self) -> Result<()> {
// test stuff
}
}
#[cfg(not(test))]
impl Write for DB {
fn write(&mut self, buf: &[u8]) -> Result<usize> {
// actually write
}
fn flush(&mut self) -> Result<()> {
// actually flush
}
}
If you forget to implement the not(test)
version, you will get a compilation error.