-
Greetings! I got some ephemeral client: #[cfg(test)]
use mockall::{automock, mock, predicate::*};
use std::sync::mpsc::{channel, Receiver, Sender};
use std::thread::spawn;
//#[cfg_attr(test, automock)]
pub struct Client {
tx: Sender<Box<str>>,
rx: Receiver<(u16, Box<str>)>,
}
#[cfg_attr(test, automock)]
impl Client {
pub fn new() -> Self {
let (in_tx, in_rx) = channel();
let (out_tx, out_rx) = channel();
spawn(move || loop {
match in_rx.recv() {
Ok(msg) => out_tx.send((0, msg)).unwrap(),
Err(err) => {
out_tx
.send((u16::MAX, err.to_string().into_boxed_str()))
.unwrap();
break;
}
}
});
Self {
tx: in_tx,
rx: out_rx,
}
}
pub fn send(&self, msg: Box<str>) -> (u16, Box<str>) {
self.tx.send(msg).unwrap();
self.rx.recv().unwrap()
}
} and I have some ephemeral context: #[cfg(test)]
use mockall::{automock, mock, predicate::*};
use crate::Client;
//#[cfg_attr(test, automock)]
pub struct Context {
client: Client,
}
#[cfg_attr(test, automock)]
impl Context {
pub fn new(client: Client) -> Self {
Self { client }
}
pub fn handshake(&self) -> bool {
match self.client.send("handshake".into()) {
(0, msg) => {
println!("Got OK handshake response `{msg}`.");
true
}
(status, msg) => {
eprintln!("Got {status} handshake response `{msg}`.");
false
}
}
}
} How can I use mocked #[cfg(test)]
mod test {
use super::{client::Client, context::Context};
#[test]
fn test_mock() {
let mut client_mock = Client::default();
client_mock.expect_send().returning(|msg| (0, msg));
let context = Context::new(client_mock);
assert!(context.handshake());
let mut client_mock = Client::default();
client_mock
.expect_send()
.returning(|msg| (u16::MAX, "ERROR".into()));
let context = Context::new(client_mock);
assert!(!context.handshake());
}
} |
Beta Was this translation helpful? Give feedback.
Answered by
asomers
Aug 17, 2022
Replies: 1 comment 1 reply
-
Are you expecting your MockContext to call the |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
BratSinot
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Are you expecting your MockContext to call the
MockClient::send
method? It won't, because it's a mock Context and not a real one. Why are you mocking Context at all? I think you want to use a real Context object.