Skip to content

Support mocking delegate types (#48)#60

Merged
tillig merged 1 commit into
developfrom
feature/issue-48-delegate-mock
Jun 29, 2026
Merged

Support mocking delegate types (#48)#60
tillig merged 1 commit into
developfrom
feature/issue-48-delegate-mock

Conversation

@tillig

@tillig tillig commented Jun 29, 2026

Copy link
Copy Markdown
Member

Fixes #48.

Problem

AutoMock.Mock<T>() cast the resolved object to IMocked<T>:

var obj = (IMocked<T>)Create<T>(true, parameters);
return obj.Mock;

For interfaces and classes, Moq's proxy .Object implements IMocked<T>, so this works. But for a delegate mock, .Object is the delegate itself and does not implement IMocked<T>, so the cast threw:

Unable to cast object of type 'MyDelegate' to type 'Moq.IMocked`1[MyDelegate]'.

Fix

Use Moq.Mock.Get(...) instead of the cast. Mock.Get retrieves the Mock<T> from Moq's internal registry rather than relying on the resolved object implementing IMocked<T>, so it works for delegate mocks as well as interfaces and classes.

Tests

Added a regression test that mocks a delegate type, sets it up, and invokes it. Full suite passes (49 tests).

Mock<T>() now uses Moq.Mock.Get instead of casting the resolved object to
IMocked<T>. A delegate mock's Object is the delegate itself and does not
implement IMocked<T>, so the previous cast threw InvalidCastException.
@codecov

codecov Bot commented Jun 29, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.90%. Comparing base (595df74) to head (5623078).

Additional details and impacted files
@@             Coverage Diff             @@
##           develop      #60      +/-   ##
===========================================
- Coverage    90.99%   90.90%   -0.09%     
===========================================
  Files            3        3              
  Lines          111      110       -1     
  Branches        21       21              
===========================================
- Hits           101      100       -1     
  Misses           6        6              
  Partials         4        4              

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@tillig
tillig merged commit 0379436 into develop Jun 29, 2026
12 checks passed
@tillig
tillig deleted the feature/issue-48-delegate-mock branch June 29, 2026 21:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

AutoMock fails creating a mock for a delegate type

1 participant