简体   繁体   中英

How do I use MiniTest::Mock to assert that a 'verify' method has been called on a mocked object?

I have a class that defines a 'verify' method which is unfortunately the same name that MiniTest::Mock uses to verify a method has been called. I'm running into a clobbering problem.

I have classes defined as below.

class Reader
  def initialize(verifier)
    @verifier = verifier
  end

  def verify(subject)
    @verifier.verify(subject)
  end
end

class Verifier
  def verify(subject)
    subject != nil
  end
end

I have tests setup as follows.

class TestReader < MiniTest::Test
  def test_reader_when_verification_fails
    mock_verifier = MiniTest::Mock.new
    mock_verifier.expect :verify, false

    reader = Reader.new(mock_verifier)
    reader.verify(nil)

    # The following verify method ends up being the 'verify' defined on
    # Verifier, not on MiniTest::Mock. It blows up because Verifier#verify
    # expects an argument.
    mock_verifier.verify
  end
end

How do I get around this?

EDIT: Original post (at bottom) was incorrect.

A working solution is:

@mock_verifier.instance_eval {
        def assert
            @expected_calls.each do |name, expected|
                actual = @actual_calls.fetch(name, nil)
                raise MockExpectationError, "expected #{__call name, expected[0]}" unless actual
                raise MockExpectationError, "expected #{__call name, expected[actual.size]}, got [#{__call name, actual}]" if
                    actual.size < expected.size
            end
            true
        end
}

* Below is incorrect *

Open up the mock, save off the MiniTest::Mock#verify method under a different method name (The -> Proc is needed to capture scope), then un-define 'verify' on the mock.

def @mock_verifier.assert  
  -> { @mock_verifier.method(:verify) }
end

@mock_verifier.instance_eval 'undef :verify'

Now at the end you do

@mock_verifier.expect :verify, false

@reader.verify(nil)

@mock_verifier.assert

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM