How do you mock a class using the readonly property?

Any idea in Moq for a class with readonly modifier:

Class myClass { private int id; public int Id{ get {return id;}} public myClass(int id) { this.id = id } } 

I tried to mock this object:

 var myMock= new Mock<myClass>(); myMock.SetupGet(m => m.ID).Return(555); 

He returned me an error:

System.ArgumentException: Invalid setting on non-overlapping element m => m.ID.

Any idea?

+4
source share
2 answers

The problem is not that it is read-only, but that it is not virtual.

+11
source

The only mocking engine that I know about this allows you to change non-virtual methods for classes and private classes - Typemock.

Most other mocking frameworks work better with interfaces, and if the interface is not available, the members who taunt should be virtual.

+2
source

Source: https://habr.com/ru/post/1286439/


All Articles