nsubstitute / NSubstitute

A friendly substitute for .NET mocking libraries.
https://nsubstitute.github.io
Other
2.67k stars 263 forks source link

.NET Core - HttpWebRequest #245

Closed jirisykora83 closed 7 years ago

jirisykora83 commented 8 years ago

In .NET Core not working this code. But same code working on full .NET.

HttpWebRequest webRequestMock = Substitute.For<HttpWebRequest>();

Error message: Parent does not have a default constructor. The default constructor must be explicitly defined.

StackTrace:

at System.Reflection.Emit.TypeBuilder.DefineDefaultConstructorNoLock(MethodAttributes attributes)
at System.Reflection.Emit.TypeBuilder.DefineDefaultConstructor(MethodAttributes attributes)
at System.Reflection.Emit.TypeBuilder.CreateTypeNoLock()
at System.Reflection.Emit.TypeBuilder.CreateTypeInfo()
at Castle.DynamicProxy.Generators.Emitters.AbstractTypeEmitter.CreateType(TypeBuilder type)
at Castle.DynamicProxy.Generators.Emitters.AbstractTypeEmitter.BuildType()
at Castle.DynamicProxy.Generators.ClassProxyGenerator.GenerateType(String name, Type[] interfaces, INamingScope namingScope)
at Castle.DynamicProxy.Generators.BaseProxyGenerator.ObtainProxyType(CacheKey cacheKey, Func`3 factory)
at Castle.DynamicProxy.ProxyGenerator.CreateClassProxy(Type classToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options, Object[] constructorArguments, IInterceptor[] interceptors)
at NSubstitute.Proxies.CastleDynamicProxy.CastleDynamicProxyFactory.GenerateProxy(ICallRouter callRouter, Type typeToProxy, Type[] additionalInterfaces, Object[] constructorArguments)
at NSubstitute.Core.SubstituteFactory.Create(Type[] typesToProxy, Object[] constructorArguments, SubstituteConfig config)
at NSubstitute.Substitute.For[T](Object[] constructorArguments)
...
alexandrnikitin commented 8 years ago

I'm sorry I didn't dig deep but it turns out that the HttpWebRequest class was changed in .NET Core version. var ctrs = typeof(HttpWebRequest).GetConstructors(); gives you an empty array while it returns a constructor in .NET version.

jirisykora83 commented 8 years ago

@alexandrnikitin I look on currently TypeExtensions source code via decompiler and it's look currently .NET Core doesn't support GetConstructors();

public static ConstructorInfo[] GetConstructors(this Type type) { return (ConstructorInfo[]) null; }

alexandrnikitin commented 8 years ago

@jirisykora83 I wouldn't be surprised if they shipped that not implemented version. But hopefully they didn't. https://github.com/dotnet/corefx/blob/release/1.0.0/src/System.Reflection.TypeExtensions/src/System/Reflection/TypeExtensions.CoreCLR.cs

jirisykora83 commented 8 years ago

I again try look on typeof(HttpWebRequest) and here what a i get.

image

I think it's have constructors (non-public) but it's look currently GetConstructors(); not support non-public.

dtchepak commented 7 years ago

Could not reproduce this with NSub 3.0 and .NET Core 2.0. Please re-open is this is still an issue.