Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I mock a method on an object without a default constructor?

Tags:

c#

moq

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?

like image 290
ryeguy Avatar asked Jun 18 '11 05:06

ryeguy


People also ask

How do you mock a class without a default constructor?

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);

Can you mock an object?

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.

How do I mock a class without an interface?

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.

Can you call method on mocked object?

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.


1 Answers

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.

like image 69
Phil Sandler Avatar answered Nov 01 '22 16:11

Phil Sandler