Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::io::prelude::*;
- trait Interface {
- fn message(&mut self, message: &str);
- }
- struct Console {
- write: Box<dyn Write>,
- }
- impl Console {
- fn new(write: Box<dyn Write>) -> Self {
- Self { write }
- }
- }
- impl Interface for Console {
- fn message(&mut self, message: &str) {
- write!(self.write, "{}", message).expect("Welp 🤷♂️")
- }
- }
- fn main() {
- let mut console: Box<dyn Interface> = Box::new(Console::new(Box::new(std::io::stdout())));
- console.message("Hello World");
- }
- #[cfg(test)]
- mod test {
- use super::{Console, Interface};
- use std::io::prelude::*;
- struct MockWriter {
- written: Vec<Vec<u8>>,
- }
- impl MockWriter {
- fn new() -> Self {
- Self {
- written: vec![vec![]],
- }
- }
- }
- impl Write for MockWriter {
- fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
- self.written.push(buf.to_vec());
- Ok(buf.len())
- }
- fn flush(&mut self) -> std::io::Result<()> {
- Ok(())
- }
- }
- fn make_test_console() -> Console {
- Console::new(Box::new(MockWriter::new()))
- }
- #[test]
- fn test_message() {
- // Arrange
- let mut console = make_test_console();
- // Act
- console.message("Hello World");
- // Assert
- // How to assert on the content of `MockWriter` here without changing
- // the type of `write` in `Console`?
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement