79142471

Date: 2024-10-30 18:59:55
Score: 0.5
Natty:
Report link

Based on the followup discussion with kmdrenko, better solution was found. I didn't want to replace first answer because it had some discussion.

In this solution use of that Rc clone is isolated to own scope and Rc::get_mut is used to get mutable access to mock after there are no other Rc's referring to it.

#[test]
fn test_sage() {
    let mut mock_source = MockWisdomSource::new();
    mock_source.expect_ask().times(1).return_const("42".to_string());

    let mut mockup_rc = Rc::new(mock_source);

    // Scope to drop Oracle before checking the mockup
    {
        let source = Rc::clone(&mockup_rc) as Rc<dyn WisdomSource>;        
        let oracle = Oracle{source};
        
        let answer = oracle.ask(&"What is the meaning of life?".to_string());

        assert_eq!(answer, "42");
    }
     
    // Check that the mockup was called
    let mock_ref = Rc::get_mut(&mut mockup_rc).unwrap();
    mock_ref.checkpoint();        
}
Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Self-answer (0.5):
  • Low reputation (1):
Posted by: Heikki Taavettila