Make method only callable from unit test

Is it possible to write methods that can only be called by unit tests? My problem is that our structure contains many Singleton classes, which makes unit testing pretty complicated. My idea was to create a simple interface:

 public interface IUnitTestClearable { void ClearForUnitTest(); } 

This method will be called to "dump" single instances to better handle unit tests. But this method should only be called from unit test classes / instances. Is it possible?

+5
source share
3 answers

You can make the method internal and set InternalsVisibleTo. This way you give another assembly access to your internal devices

http://geekswithblogs.net/jwhitehorn/archive/2007/11/09/116750.aspx

but Tim was in front of me as I finish it :)

In the project file AssemblyInfo.cs set

 [assembly: InternalsVisibleTo("Application.Test")] 

or if you have a signed assembly

 [assembly: InternalsVisibleTo("Application.Test, PublicKey=KEYHERE")] 
+8
source

Giving access to unit tests while monitoring or preventing other things (ab) using this access is a good idea. There are several ways to do this, but the easiest is to use InternalsVisibleTo

https://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx

+5
source

You may not want to expose all private methods to your unit tests, as this can be confusing, so just add a private method for your singleton classes.

 public class MySingleton { private void ClearForUnitTest() { Console.WriteLine("Cleared."); } } 

Create an extension to be used in your unit tests.

 public static class PrivateExtensions { public static void ClearForUnitTest<T>(this T instance) { var method = typeof(T).GetMethod("ClearForUnitTest", BindingFlags.NonPublic | BindingFlags.Instance); method.Invoke(instance, null); } } 

Use as if it will be publicly available

 private static void Main(string[] args) { var ms = new MySingleton(); ms.ClearForUnitTest(); } 

profit

+1
source

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


All Articles