简体   繁体   中英

Testing (not unit testing) private method correctness

Let's say I write a private method which has a string as an argument and returns a string.

private string SomeMethod(string a)
{ ... }

After writing it, I want to make sure this method works correctly and input a sample string to see what the return value is. Now I test it the following way. I either:

  • comment out everything I have in main() function and call just the method SomeMethod() or
  • I call the method where it should be called in the code, set the breakpoint at that place and debug to see if the return value was correct.

I don't like either method. Is there any better way to simply check and test the method while developing code? I can't (shouldn't) write a unit test for this method as it's private.

If you just want to test it once after creating it, I would recommend to keep another instance of your Development Environment (eg Visual Studio) open, with a simple console application where you can just copy-paste the function and test it there.

If you want it regularly tested to ensure it doesn't go wrong with later changes, then I fear Unit testing is exactly what you need. You might use precompiler flags to disable the private scope for testing purposes:

#define TESTING
(...)
#if TESTING
        public void foo()
#else
        private void foo()
#endif

This is the academia approach for all first year classes at the University of Waterloo, I imagine a similar approach is taken in the real world (my first co-op is 2014 so I don't know just yet). I find it very useful but it takes some time.

If you create a class (henceforth mentioned as a module) then you need you create an associative driver module for each class. This driver file will consist of all your tests: testing edge cases and expected input to ensure your function(s) from your module behave as expected. Each driver module will have a main method and for your testing you will need to change the scope of your function from private to public (or call them all in the constructor).

Keep in mind we are programming in C and driver modules are much easier to make without changing scope (the occasional static for modular scope).

Put the logic in a public method, which you unit test while your are developing. When you are satisfied you have got the logic correct, you can copy and paste the logic in to your private method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM