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
236 views
in Technique[技术] by (71.8m points)

c# - Moq and validating a private method ios called with correct parameters

I'm probably below average on Unit Testing skills, but been asked to write a unit test for something I fixed. Basically, a method now allows a null value to be passed in, and I need to validate that it gets switched to the correct value, if null.(Please note, method code reduced to remove supurfluous code - it actually does more than return true...)

 public IDictionary<string, JToken> MethodINeedToTest(
            long? userId,
            long? orgId
        )
 {
       userId ??= DataServicesHelper.SystemUserKey;
            
       var myResults = APrivateMethod(userId.Value, orgId, false);

       return true;
}

I was hoping to just verify that APrivateMethod was called with the value from DataServicesHelper.SystemUserKey. However, the method is private. So with Moq, I cannot do a verify on a private method (I believe).

Is there anyway to validate that when userId is passed in as null, the method is called with DataServicesHelper.SystemUserKey? (Other test is to validate that it gets called with userId when it's not null).

Or is the code just not testable?

question from:https://stackoverflow.com/questions/65910827/moq-and-validating-a-private-method-ios-called-with-correct-parameters

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

1 Reply

0 votes
by (71.8m points)

I think in this case there are 2 options.

  1. Just let the APrivateMethod execute as is without any mocks and you validate the result that you get in both cases.
  2. If option 1 is not possible due to the private method calling any outside service/repository then in that case you should try to use DI to inject those external dependencies that are used by the private method and then mock out those external calls.

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

...