Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2019
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.51 KB | None | 0 0
  1. use std::io::prelude::*;
  2.  
  3. trait Interface {
  4. fn message(&mut self, message: &str);
  5. }
  6.  
  7. struct Console {
  8. write: Box<dyn Write>,
  9. }
  10.  
  11. impl Console {
  12. fn new(write: Box<dyn Write>) -> Self {
  13. Self { write }
  14. }
  15. }
  16.  
  17. impl Interface for Console {
  18. fn message(&mut self, message: &str) {
  19. write!(self.write, "{}", message).expect("Welp 🤷‍♂️")
  20. }
  21. }
  22.  
  23. fn main() {
  24. let mut console: Box<dyn Interface> = Box::new(Console::new(Box::new(std::io::stdout())));
  25. console.message("Hello World");
  26. }
  27.  
  28. #[cfg(test)]
  29. mod test {
  30. use super::{Console, Interface};
  31. use std::io::prelude::*;
  32.  
  33. struct MockWriter {
  34. written: Vec<Vec<u8>>,
  35. }
  36.  
  37. impl MockWriter {
  38. fn new() -> Self {
  39. Self {
  40. written: vec![vec![]],
  41. }
  42. }
  43. }
  44.  
  45. impl Write for MockWriter {
  46. fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
  47. self.written.push(buf.to_vec());
  48.  
  49. Ok(buf.len())
  50. }
  51.  
  52. fn flush(&mut self) -> std::io::Result<()> {
  53. Ok(())
  54. }
  55. }
  56.  
  57. fn make_test_console() -> Console {
  58. Console::new(Box::new(MockWriter::new()))
  59. }
  60.  
  61. #[test]
  62. fn test_message() {
  63. // Arrange
  64. let mut console = make_test_console();
  65.  
  66. // Act
  67. console.message("Hello World");
  68.  
  69. // Assert
  70. // How to assert on the content of `MockWriter` here without changing
  71. // the type of `write` in `Console`?
  72. }
  73.  
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement