Using moq, if I try to mock a method directly on Foo
, I get this: Invalid verify on a non-virtual (overridable in VB) member.
My alternative is to mock IFoo
, which gets rid of the above problem, but then I can't construct it because Foo
does not have a paramaterless constructor (Constructor arguments cannot be passed for interface mocks.
). What can I do?
You need to use a different overload of the Mock ctor so that arguments are passed to the non-default Foo ctor: var mockObject = new Mock<Foo>(1, 2);
We can use Mockito class mock() method to create a mock object of a given class or interface. This is the simplest way to mock an object. We are using JUnit 5 to write test cases in conjunction with Mockito to mock objects.
Simply mark any method you need to fake as virtual (and not private). Then you will be able to create a fake that can override the method. Save this answer.
Mockito allows us to partially mock an object. This means that we can create a mock object and still be able to call a real method on it.
You should be able to mock IFoo without problem, and you would have no reason to pass arguments when you are mocking an interface. Your IFoo mock will be exactly that (a mock!), and will have no knowledge of Foo or any real implementation, so passing constructor arguments would not make sense.
Edit: I would add that mocking an interface if one exists is almost always preferable to mocking a concrete implemention. If you only have a concrete implementation, the fact that you want to mock it probably means it would be a good candidate for adding an interface.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With