简体   繁体   中英

Moq Static Implicit Operator Using MsTest

I have a abstract class Enumeration which implements the IComparable interface.

public abstract class Enumeration : IComparable
{         
    [JsonConstructor]
    protected Enumeration(int id, string name)
    {
        Id = id;
        Name = name;
    }

    public int Id { get; }
    
    public string Name { get; }
   
    public static implicit operator Enumeration(string name)
    {
        return GetAll<Enumeration>().FirstOrDefault(i => i.Name == name);
    }
    
    public static IEnumerable<TEnumeration> GetAll<TEnumeration>() where TEnumeration : Enumeration
    {
        var fields = typeof(TEnumeration).GetFields(
            BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly);

        return fields.Select(fieldInfo => fieldInfo.GetValue(null)).Cast<TEnumeration>();
    }

I have created SampleStatus.cs class which is inherits from Enumeration.cs class.

    public class SampleStatus : Enumeration
    { 
        public static readonly SampleStatus Completed = new SampleStatus(1, nameof(Completed));    
         
        public static readonly SampleStatus Deleted = new SampleStatus(2, nameof(Deleted));    
        
        public SampleStatus(int id, string name) : base(id, name)
        {
        }              
    }

I have created unit test class for SampleStatus.cs class.

    [TestMethod]
    public void TestMethod()
    {
        // arrange and act             
        var result = (Enumeration)SampleStatus.GetAll<SampleStatus>().Single(x => x.Id == 1).Name; // output is returning null.

        // assert
        Assert.AreEqual("Completed", result);
    }

When I call GetAll method which is returning null. I have mocked GetAll and Implicit operator method in the above code.

In provided sample GetAll does not return null (if it did - I would get NullReferenceException ). Issue with the sample is in the cast to Enumeration . SampleStatus.GetAll<SampleStatus>().Single(x => x.Id == 1).Name results in Completed which you then cast to Enumeration . Since the implicit conversion exists and the base class does not have definition for Completed (Enumeration)"Completed" ends up being null (ie GetAll<Enumeration>().FirstOrDefault(i => i.Name == name)) ).

You can fix it with removing cast for example:

[TestMethod]
public void TestMethod()
{
    // arrange and act             
    var result = SampleStatus.GetAll<SampleStatus>().Single(x => x.Id == 1).Name; // output is returning null.

    // assert
    Assert.AreEqual("Completed", result);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM