Skip to content

Test Explorer in VS 2022/2026 can run but not debug test with DynamicData that uses field initialized in ClassInitialize #7774

@abatishchev

Description

@abatishchev

Describe the bug

Given a test decorated with [DynamicData] which points to a method that uses a static field which is initialized by a method decorated with [ClassInitialize], it works well (runs and green) in both Test Explorer -> Run and in ADO. But it fails with a NullReferenceException in Test Explorer -> Debug because the field is null.

Version used

MSTest.Sdk version 4.2.1

VS 2022 version 17.14.31
or
VS 2026 version 18.5.0

Steps To Reproduce

csproj file:

<Project Sdk="MSTest.Sdk/4.2.1">
  <PropertyGroup>
    <TargetFramework>net9.0</TargetFramework>
    <LangVersion>latest</LangVersion>
    <Nullable>annotations</Nullable>
    <EnableMSTestRunner>true</EnableMSTestRunner>
    <PreserveCompilationContext>true</PreserveCompilationContext>
    <TestingPlatformShowTestsFailure>true</TestingPlatformShowTestsFailure>
  </PropertyGroup>
</Project>

cs file:

using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace FoldUnfoldRunDebugTest1
{
    [TestClass]
    public sealed class Test1
    {
        private static ResourceProviderConfig _config;

        [ClassInitialize]
        public static void ClassInitialize(TestContext context) =>
            _config = new ResourceProviderConfig(context);

        [DynamicData(nameof(GetKinds))]
        [TestMethod]
        public void Create_And_Delete_ThrottlingAccount_Using_HttpArmClient_Should_Succeed(string kind)
        {
            Assert.IsNotNull(kind);
        }

        private static IEnumerable<object[]> GetKinds()
        {
            yield return [_config.KindPrefix + Guid.NewGuid()];
        }

        public sealed class ResourceProviderConfig
        {
            public ResourceProviderConfig(TestContext _)
            {
            }

            public string KindPrefix => "kind-";
        }
    }
}

Expected behavior

  1. Test Explorer, right click -> Run works
  2. Test Explorer, right click -> Debug works

Actual behavior

  1. Test Explorer, right click -> Run works
  2. Test Explorer, right click -> Debug fails with a NullReferenceException

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions