Test code for enum - enums

If I am declaring 2 enums inside my class this way:
public class EnumerationExample {
public enum Season {WINTER,SPRING,SUMMER,FALL}
public enum Month {JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC}
public List<Month> listMonths;
public Month convert (String val) {
for (Month mtObj : Month.values()) {
if (mtObj.name() == val) {
system.debug('The value passed is ' +mtObj);
}
}
return null;
}
public List<Month> seasonMonths(Season s) {
Season seasonObj = Season.SPRING;
listMonths = new List<Month>();
if(s==season.WINTER) {
listMonths.add(Month.DEC);
listMonths.add(Month.JAN);
listMonths.add(Month.FEB);
}
else if(s==season.SPRING) {
listMonths.add(Month.MAR);
listMonths.add(Month.APR);
listMonths.add(Month.MAY);
}
else if(s==season.SUMMER) {
listMonths.add(Month.JUN);
listMonths.add(Month.JUL);
listMonths.add(Month.AUG);
}
else if(s==season.FALL) {
listMonths.add(Month.SEP);
listMonths.add(Month.OCT);
listMonths.add(Month.NOV);
}
return listMonths;
}
}
how do i write test code for this ??
i tried doing this way but it says season variable does not exist at line EnumerationExampleObj.seasonMonths(Season.WINTER);...
#isTest
public class TestEnumerationExample {
public static testMethod void myUnitTest() {
EnumerationExample EnumerationExampleObj = new EnumerationExample();
EnumerationExampleObj.convert('wintery');
EnumerationExampleObj.seasonMonths(Season.WINTER);
system.assertEquals(EnumerationExampleObj.listMonths.get(0) , Month.DEC );
}}
is there any problem with the access modifier or any specific annotations.?

Your problem is not related to testing at all, but to C# basics like scope and syntax (your sample code is full of syntax errors).
To answer your specific question: if you define a public enum inside a class, you have to prefix it with the class name when used outside that class. Example:
var enumerationExampleObj = new EnumerationExample();
enumerationExampleObj.seasonMonths(EnumerationExample.Season.WINTER);

Related

How do I pass parameter of type enum to a method in Apex?

public class EnumTest {
Public enum Season {Spring,Summer,fall,winter}
Public static Void SeasonFinder(Season CurrentSeason)
{
If(CurrentSeason == Season.Spring || CurrentSeason == Season.fall )
{
System.debug('Neither cold nor hot');
} else if(CurrentSeason == Season.Summer)
{
System.debug('It is hot');
} Else if(CurrentSeason == Season.Winter)
{
System.debug('It is Cold');
}
Else
{
System.debug('Invalid Season');
}
}
}
I need to call the function SeasonFinder. But how do I pass the parameter of type season? Am getting error like variable season does not exist.
You have to call it as static so the call would be like this:
seasonTest.SeasonFinder(EnumTest.Season.Summer)

Custom SchemaFilter in Swashbuckle to show enum with description but changes input value

I needed to add enum description for schema of a request in swagger, so I defined this filter :
public class EnumSchemaFilter : ISchemaFilter
{
public void Apply(OpenApiSchema model, SchemaFilterContext context)
{
if (context.Type.IsEnum)
{
model.Enum.Clear();
var names = Enum.GetNames(context.Type);
names
.ToList()
.ForEach(n => model.Enum.Add(new OpenApiString($"{n} : {(int)Enum.Parse(context.Type, n)}")));
model.Example = new OpenApiInteger((int)Enum.Parse(context.Type, names[0]));
}
}
}
However the issue here is that when I want to try that enum in a get request, I see the following option :
Is there a way to change this to only show enum integer values when user want to select ?
I could solve the issue by defining a custom ParametersFilter :
public class SchemaParametersFilter : IParameterFilter
{
public void Apply(OpenApiParameter parameter, ParameterFilterContext context)
{
var type = context.ParameterInfo?.ParameterType;
if (type == null)
return;
if (type.IsEnum && parameter.In == ParameterLocation.Query)
{
var names = Enum.GetNames(type);
parameter.Schema.Enum = names.OfType<string>().Select(p => new OpenApiInteger((int)Enum.Parse(type, p))).ToList<IOpenApiAny>();
}
}
}

need help on Unity: parameter doesn't exist in current Construct Context

I was going to practice how to create Inventory, but it seems it won't read the parameter from the other script. I'm working on my training based on my tutorial, here's how the code goes:
public class ItemCatalogue : MonoBehaviour
{
public Items[] AvailableItems;
public Text DisplayArray;
public void GetItem()
{
Items item = AvailableItems[Random.Range(0, AvailableItems.Length)];
InventoryCatalogue.Instance.AddMaterialToCatalogue(new ItemStack(FoodMaterial, amount));//weird, the parameter doesn't exist
DisplayArray.text = item.name;
}
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
}
}
And here's the other script:
[System.Serializable]
public class ItemStack
{
public Items FoodMaterial;
public int amount;
public ItemStack(Items FoodMaterial, int amount) //here's the parameter
{
this.FoodMaterial = FoodMaterial;
this.amount = amount;
}
}
i didn't expect anything because i haven't finished the tutorial. anybody know why?
well in
InventoryCatalogue.Instance.AddMaterialToCatalogue(new ItemStack(FoodMaterial, amount));
you call
new ItemStack(FoodMaterial, amount)
with the parameters FoodMaterial, amount but your ItemCatalogue class nor the method GetItem contains any variables/fields/properties with those names.
You rather have to pass some values in there like e.g.
// I don't know what you want to pass in as amount
new ItemStack(item, 1)
so
Items item = AvailableItems[Random.Range(0, AvailableItems.Length)];
InventoryCatalogue.Instance.AddMaterialToCatalogue(new ItemStack(item, 1));

Linq expression over a list of derived types

I am trying to write a Linq expression that checks against property in a derived class, but the list is made up of members from a base class. Example code below. The 2nd line of the Process method starting with 'var list' does not compile, but I am not sure what syntax I should use to make it valid?
public class Manager
{
public void Process()
{
Base[] stuff = { new Derived() { Id = "1", Name = "me" } };
var list = stuff.Where<Derived>(d => d.Name == "me");
}
}
public class Base
{
public string Id { get; set; }
}
public class Derived : Base
{
public string Name { get; set; }
}
If you know the list has only Derived, you can use the Cast<T> method:
var list = stuff.Cast<Derived>().Where(d => d.Name == "me");
If there are only some Derived, you can use OfType<T>:
var list = stuff.OfType<Derived>().Where(d => d.Name == "me");
In that case, the non-Derived objects will be skipped.

Operator overloading in Linq queries

Operator overloading is working perfect in C# code, since I am trying in the following way.
**
public class HostCode
{
public string Code { get; set; }
public string Name { get; set; }
public static bool operator ==(HostCode hc1, HostCode hc2)
{
return hc1.Code == hc2.Code;
}
public static bool operator !=(HostCode hc1, HostCode hc2)
{
return true;
}
}**
I have a clas called HostCode and it contains 2 overloading methods (one for '==' and another for '!=')
And I created a collection of Host Codes below.
**var hostCodes = new List<HostCode>()
{
new HostCode(){ Code = "1", Name = "sreekanth" },
new HostCode(){ Code = "2", Name = "sajan" },
new HostCode(){ Code = "3", Name = "mathew" },
new HostCode(){ Code = "4", Name = "sachin" }
};**
***var hc = new HostCode() { Code = "1", Name = "sreekanth" };***
***var isEq = hostCodes[1] == hc;***
when I am trying like above, the respective operator method fired in HostCode class (in this case it is '=='). So that I can write my custom logic there.
But if Iam trying with a Linq query as below, it is not firing. But in this case also Iam comparing 2 objects having same type.
**var isEqual = from obj in hostCodes where (HostCode)obj == (HostCode)hc select obj;**
Can anyone please help me to find out a way which I can compare 2 objects by Linq queries?
You can use IEqualityComparer or override equals for this purpose.
public class HostCode
{
....
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
return obj as HostCode == null ? false : (obj as HostCode).Code == Code;
}
}
And IEqualityComparer usage is when you have some equality on object and in some functions like Contain, ... you want use some specific equality:
public class EqualityComparer : IEqualityComparer<HostCode >
{
public bool Equals(HostCode x, HostCode y)
{
return y.ID == x.ID;
}
public int GetHashCode(string obj)
{
return obj.GetHashCode();
}
}
Since your question is "how should I compare them for this to work" I would answer "you should overload and use .Equals() instead of =="
And what's with your overload definition of !=?

Resources