Private Accessor class ignores common restrictions

These days I ran into the problem of testing Team System Unit. I found that the automatically created accessor class ignores common restrictions - at least in the following case:

Suppose you have the following class:

namespace MyLibrary { public class MyClass { public Nullable<T> MyMethod<T>(string s) where T : struct { return (T)Enum.Parse(typeof(T), s, true); } } } 

If you want to test MyMethod, you can create a test project with the following test method:

 public enum TestEnum { Item1, Item2, Item3 } [TestMethod()] public void MyMethodTest() { MyClass c = new MyClass(); PrivateObject po = new PrivateObject(c); MyClass_Accessor target = new MyClass_Accessor(po); // The following line produces the following error: // Unit Test Adapter threw exception: GenericArguments[0], 'T', on // 'System.Nullable`1[T]' violates the constraint of type parameter 'T'.. TestEnum? e1 = target.MyMethod<TestEnum>("item2"); // The following line works great but does not work for testing private methods. TestEnum? e2 = c.MyMethod<TestEnum>("item2"); } 

The launch of the test will fail with the error indicated in the comment of the fragment above. The problem is the accessor class created by Visual Studio. If you go to it, you go to the following code:

 namespace MyLibrary { [Shadowing("MyLibrary.MyClass")] public class MyClass_Accessor : BaseShadow { protected static PrivateType m_privateType; [Shadowing(" .ctor@0 ")] public MyClass_Accessor(); public MyClass_Accessor(PrivateObject __p1); public static PrivateType ShadowedType { get; } public static MyClass_Accessor AttachShadow(object __p1); [Shadowing(" MyMethod@1 ")] public T? MyMethod(string s); } } 

As you can see, there are no restrictions on the type parameter of the MyMethod method.

This is mistake? Is it for design? Who knows how to get around this?

+4
source share
5 answers

I vote. I do not understand how this can be by design.

+3
source

I did not check everything, but it looks like a call:

 TestEnum? e1 = target.MyMethod("item2"); 

uses type inference to determine the type type of param T. Try calling the method differently in the test, if possible:

 TestEnum? e1 = target.MyMethod<TestEnum>("item2"); 

This can give different results.

Hope this helps!

+1
source

Looks like a mistake. A workaround would be to change the method to internal and add [assembly: InternalsVisibleTo("MyLibrary.Test")] to the assembly containing the class under the test.

This would be my preferred way of testing non-public methods, as it produces many cleaner looking unit tests.

+1
source

Search for unit tests with generics in msdn. This is a known limitation. Vote for permission in Microsoft Connect, as it definitely needs permission.

0
source

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


All Articles