How to avoid code duplication with write mode in Rhino Mocks?

This is a test suite, green using Rhino Mocks.

[SetUp]
  public void BeforeEachTest()
  {
     _mocksRepo = new MockRepository();
     _mockBank = _mocksRepo.StrictMock<IBank>();
     //_mockPrinter = _mocksRepo.StrictMock<IPrinter>();
     _mockPrinter = _mocksRepo.DynamicMock<IPrinter>();
     _mockLogger = _mocksRepo.StrictMock<ILog>();

     _testSubject = new CrashTestDummy(DUMMY_NAME, _mockPrinter, _mockLogger);
  }

  [TearDown]
  public void AfterEachTest()
  {
     _mocksRepo.ReplayAll(); // 2nd call to ReplayAll does nothing. Safeguard check
     _mocksRepo.VerifyAll();
  }

  [Test]
  public void Test_ConstrainingArguments()
  {
     _mockPrinter.Print(null);
     LastCall.Constraints(Text.StartsWith("The current date is : "));
     _mocksRepo.ReplayAll();

     _testSubject.PrintDate();
  }

Now, to make a green test in another fixture, I had to make a small change to ctor - to subscribe to an event in the printer interface. This led to all tests in the above control unit being red.

public CrashTestDummy(string name, IPrinter namePrinter, ILog logger)
      {
         _printer = namePrinter;
         _name = name;
         _logger = logger;

         _printer.Torpedoed += KaboomLogger;   // CHANGE
      }

NUnit errors tab displays

LearnRhinoMocks.Rhino101.Test_ConstrainingArguments:
TearDown : System.Reflection.TargetInvocationException : Exception has been thrown by the target of an invocation.
  ----> Rhino.Mocks.Exceptions.ExpectationViolationException : IPrinter.add_Torpedoed(System.EventHandler`1[LearnRhinoMocks.MyEventArgs]); Expected #1, Actual #0.

The fix is ​​to move the line where the test object is created from Setup()below the line ReplayAll()in the test. Rhino mocks believes that you configured the event as a wait otherwise. However, this fix means (some) duplication in each test. Each test usually adds some expectations before calling ReplayAll.

, , ctor.

  • , . ModelViewPresenter , ?
  • , - , ? ?
+3
2

Mark . RhinoMocks - . , . - :


    SetupResult.For(_mockPrinter...);
    _mocksRepo.Replay(_mockPrinter);
    _testSubject = new CrashTestDummy(DUMMY_NAME, _mockPrinter, _mockLogger);
    _mocksRepo.BackToRecord(_mockPrinter, BackToRecordOptions.None);
+3

xUnit Test Patterns, :)

- , General Fixture, , .

, , xUnit Test Patterns, Fixture , NUnit. , , , System Under Test (SUT).

, BeforeEachTest Fixture, , .

General Fixture , Fixture. , .

, NUnit , , . xUnit , .

Fixture (, Implicit Setup): , Fixture . , Fixture.

, .

+1

Source: https://habr.com/ru/post/1718872/


All Articles