Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

.net - How to Mock the Internal Method of a class?

I have a class which has a internal method and i want to mock the internal method . But i am unable to mock it i.e. it is not calling the mocked function but calling the original function. Is there any way to achieve this ?

Edit:Actually i am a novice to the Moq. I have many classes and methods of the classes to test using the Moq. Many classes are internal , many have internal methods, many have not-virtual methods . And can not change the signature on the methods and classes. Can anyone please let me know how to go about testing this scenario using Moq. Or else please suggest me some other testing framework which is easy to learn and easy to work with .

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can easily mock internal virtual methods by adding the following to your AssemblyInfo.cs:

[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] // namespace in Moq
[assembly: InternalsVisibleTo("YourTestClass")]

If your assembly is strongly named, you'll need to include the public key for DynamicProxyGenAssembly2 (Thanks to comment by @bvgheluwe; source: Moq quickstart guide):

[assembly:InternalsVisibleTo("DynamicProxyGenAssembly2,PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]

I don't understand why the accepted answer says you should never do it. Isn't that what you do when you use the 'Extract and Override' (local factory method) dependency injection technique outlined by Roy Osherove in Chapter 3 of The Art Of Unit Testing?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...