mardi 11 août 2020

Static context is null after been set

This .Net Core 3.1 (NUnit 3) test works under Visual Studio 2019.

But as soon I use JetBrains Rider the test fails because the static property (DataA) returns null in mostly all contexts.

Has some a idea what goes wrong and how to solve this issue?

public static class ClassA
{
    public static string DataA { get; set; }
    public static string DataB { get; set; }
    
    public static void SetAppConfig(string appSettingsPfad)
    {
        IList<JProperty> appSettings = JsonConvert.DeserializeObject<JToken>(appSettingsPfad).Select(j => (JProperty)j).ToList();

        var appKonfiguration = typeof(ClassA).GetProperties(BindingFlags.Public | BindingFlags.Static);

        foreach (JProperty property in appSettings)
        {
            var appKonfigurationProperty = appKonfiguration.SingleOrDefault(p => p.Name.Equals(property.Name, StringComparison.OrdinalIgnoreCase));
            var value = ((JValue)property.Value).Value;

            if (appKonfigurationProperty != null)
                appKonfigurationProperty.SetValue(null, Convert.ChangeType(value, appKonfigurationProperty.PropertyType));
        }
    }
}

[TestFixture]
public class DummyTest
{
    [Test]
    public void TestA()
    {
        LoadAppConfig();
        
        // DataA returns null here
        Console.WriteLine(ClassA.DataA);
        
        new BusinessLogicClass.DoSomething();
        // [...]
    }
    
    private void LoadAppConfig() {
        // [...]
        string appSettings = File.ReadAllText(jsonConfigFiles.Single());
        ClassA.SetAppConfig(appSettings);
        
        // here it works and a result is the proper string
        Console.WriteLine(ClassA.DataA);
        // [...]
    }
}

public class BusinessLogicClass {
    
    public void DoSomething() {
        // DataA returns null here
        Console.WriteLine(ClassA.DataA);
        // [...]
    }
}

(I have simplfied this code to the bare minimum, the orginal code would run into a Exception after a null check)





Aucun commentaire:

Enregistrer un commentaire