Hello,
I am currently writing a test in which a trait has a function to a non mutable reference to it self. Because of this non mutability, I cannot store the data from the write
function of the manager in the TestBlockdevice
. One possiblity to make the self of the write function in the Blockdevice trait mutable, but I have to do this only for the test, otherwise non mutable is fine.
Is there another way?
trait Blockdevice {
fn write(&self, data: &[&str]);
}
struct DummyBlockdevice {
}
impl Blockdevice for DummyBlockdevice {
fn write(&self, data: &[&str]) {
// Write data out, no mutable of self required
}
}
struct Manager<D> {
d: D
}
impl<D: Blockdevice> Manager<D> {
fn new(d: D) -> Self {
Self {
d
}
}
fn write(&self, string: &[&str]) {
self.d.write(string);
}
fn block_device(&self) -> &D {
&self.d
}
}
pub fn main() {
}
#[cfg(test)]
mod tests {
use super::*;
struct TestBlockdevice {
}
impl Blockdevice for TestBlockdevice {
fn write(&self, data: &[&str]) {
// store data so it can be retrived afterwards
// One possibility: &self -> &mut self but only required for the test
}
}
impl TestBlockdevice {
fn get_data(&self) {
// Get back stored string to check if everything was correct
}
}
#[test]
fn write_test() {
let m = Manager::new(TestBlockdevice {});
m.write(&["Test"]);
let bd = m.block_device();
let data = bd.get_data();
// check that data is correct
}
}