Skip to content

System.InvalidCastException when using custom data type converter & running tests with "dotnet test" #6713

@jon-erik-klint

Description

@jon-erik-klint

The bug

I'm getting System.InvalidCastException error when running my tests with library version 3.11.0 or higher using "dotnet test" command. The error does not appear in older versions or when runnign tests with Visual Studio built-in test runner.

The error:
System.InvalidCastException: [A]ExampleDataType cannot be cast to [B]ExampleDataType. Type A originates from 'TestProjectName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'LoadFrom' at location 'TestProjectPath\bin\Release\net48\TestProjectName.dll'. Type B originates from 'TestProjectName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'Default' at location 'ResultsDirectoryFolder\DeployFolder\Out\TestProjectName.dll'

This happens when using custom TypeConverter and using TypeDescriptor.GetConverter for accessing that TypeConverter - and then using static type reference to cast object in type converter.

Steps To Reproduce

Add the following test method and helper classes to a test project test class. Then run "dotnet test pathToTestProjectCsproj"

[TestMethod]
public void Example()
{
    object value = new ExampleDataType();
    var converter = TypeDescriptor.GetConverter(typeof(ExampleDataType));
    converter.ConvertTo(null, null, value, null); // throws the error
}

[TypeConverter(typeof(ExampleDataTypeTypeConverter))]
public class ExampleDataType
{
}

public class ExampleDataTypeTypeConverter : TypeConverter
{
    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) => true;

    public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) => true;

    public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) => new ExampleDataType();

    public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) => (ExampleDataType)value;
}

Expected behavior

No error happens, type is casted as usual (like before version 3.11.0)

Actual behavior

The mentioned exception is thrown.

Metadata

Metadata

Assignees

Labels

Area: MSTestIssues with MSTest that are not specific to more refined area (e.g. analyzers or assertions)Regression

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions