Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can MOQ Mock a Class

Tags:

moq

is it legal to MOQ a class that does not inherit an interface like so:

var mockIActionService = new Mock<IActionService>();
var mockValidAgeRule = new Mock<ValidAgeRule>(mockIActionService.Object);

I inject the IService into ValidAgeRule which is just a simple class with one method called "Excute". My question is how to I verify that has been called. Whenever I try:

 mockValidAgeRule.Verify(x => x.Execute(app)); //Where App is a valid object

does anyone know how to do this?

like image 226
jquery auth Avatar asked Sep 20 '10 15:09

jquery auth


People also ask

How do you 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. This leaves me wonder if it is necessary at all to create an interface for every class I want to mock.

Can you mock a concrete class?

5 Answers. Show activity on this post. In theory there is absolutely no problem mocking a concrete class; we are testing against a logical interface (rather than a keyword interface ), and it does not matter whether that logical interface is provided by a class or interface . In practice .

What is Moq used for?

Moq is a mocking framework built to facilitate the testing of components with dependencies. As shown earlier, dealing with dependencies could be cumbersome because it requires the creation of test doubles like fakes. Moq makes the creation of fakes redundant by using dynamically generated types.

Can you mock a private method Moq?

Moq supports mocking protected methods. Changing the methods to protected , instead of private , would allow you to mock their implementation.


1 Answers

I believe you need to make your Execute method virtual.

My understanding is that Moq creates a subclass of your class in this case, and needs to override your method in order to keep track of whether it has been called.

like image 152
Jeff Ogata Avatar answered Sep 24 '22 17:09

Jeff Ogata