Add ReferenceMockRegistry

This commit is contained in:
Michael Miller 2022-05-14 23:31:57 -06:00
parent 0704fd2a48
commit 380d721fad
No known key found for this signature in database
GPG key ID: AC78B32D30CE34A2
3 changed files with 57 additions and 4 deletions

View file

@ -1,5 +1,6 @@
require "./method_call"
require "./mocked"
require "./reference_mock_registry"
require "./stub"
require "./stubbed_name"
require "./value_stub"
@ -51,12 +52,14 @@ module Spectator
{{base}} ::{{type.name}}
include ::Spectator::Mocked
@@_spectator_stubs = Hash(self, Array(::Spectator::Stub)).new do |hash, key|
hash[key] = [] of ::Spectator::Stub
end
{% if type.class? %}
@@_spectator_mock_registry = ::Spectator::ReferenceMockRegistry.new
{% else %}
{% raise "Unsupported type for injecting mock" %}
{% end %}
private def _spectator_stubs
@@_spectator_stubs[self]
@@_spectator_mock_registry[self]
end
# Returns the mock's name formatted for user output.

View file

@ -0,0 +1,27 @@
require "./stub"
module Spectator
# Stores collections of stubs for mocked reference (class) types.
#
# This type is intended for all mocked reference types that have functionality "injected."
# That is, the type itself has mock functionality bolted on.
# Adding instance members should be avoided, for instance, it could mess up serialization.
# This registry works around that by mapping mocks (via their memory address) to a collection of stubs.
# Doing so prevents adding data to the mocked type.
class ReferenceMockRegistry
@object_stubs : Hash(Void*, Array(Stub))
# Creates an empty registry.
def initialize
@object_stubs = Hash(Void*, Array(Stub)).new do |hash, key|
hash[key] = [] of Stub
end
end
# Retrieves all stubs defined for a mocked object.
def [](object : Reference) : Array(Stub)
key = Box.box(object)
@object_stubs[key]
end
end
end