This repository has been archived by the owner on Jun 30, 2023. It is now read-only.
Replies: 1 comment 16 replies
-
This is not a Moq issue, but a design issue. A protected field (non-readonly even!) can be overwritten by anyone at any point. Not a great design to preserve the invariants of the class. If you need to expose internal state just for verification in tests, I'd suggest creating internal members that expose whatever you need and perform regular state assertions on the resulting (mock) object itself. You can make those members visible with InternalsVisibleTo easily. That said, having your tests so deeply tied to internal object state is a recipe for brittle tests that need to be constantly changed whenever implementations (inevitably) evolve. |
Beta Was this translation helpful? Give feedback.
16 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi folks! 👋
Summary
As far as I know, Moq doesn't provide direct access to
protected
class members. You can callProtectedExtension.Protected<T>(Mock<T> mock)
to setup the mock'sprotected
members, but you can't directly get/setprotected
properties/fields, and you can't directly callprotected
methods. This can make it difficult to mock a base class and test the base class's functionality.Example
Suppose that you have the following:
Since
_commonField
is used by implementors, I would argue that you should create a unit test for the_commonField
property. Ideally, you would do this by using the partial mock feature withBaseClass
. This unit test would validate that_commonField
is getting set correctly in the constructor; that way you can validate that the correct value is getting provided toFirstImplementation
andSecondImplementation
.The concern is that Moq doesn't provide direct access to the
_commonField
field, so you can't verify that it is getting set correctly. Instead, you either have to (a) create your own mock or (b) use reflection.Beta Was this translation helpful? Give feedback.
All reactions