-
Notifications
You must be signed in to change notification settings - Fork 123
Expand file tree
/
Copy pathIEnumTest.cs
More file actions
389 lines (312 loc) · 14.4 KB
/
Copy pathIEnumTest.cs
File metadata and controls
389 lines (312 loc) · 14.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
using System.Text.Json;
using System.Text.Json.Serialization;
using Adyen.Core;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Adyen.Test.Core
{
[TestClass]
public class IEnumTest
{
[TestMethod]
public async Task Given_Enums_When_Equal_Returns_Correct_True()
{
ExampleEnum? nullEnum = null;
Assert.AreEqual(nullEnum, nullEnum);
Assert.AreEqual(ExampleEnum.A, ExampleEnum.A);
Assert.AreEqual(ExampleEnum.B, ExampleEnum.B);
}
[TestMethod]
public async Task Given_Enums_When_NotEqual_Returns_Correct_False()
{
ExampleEnum? nullEnum = null;
Assert.AreNotEqual(ExampleEnum.A, ExampleEnum.B);
Assert.AreNotEqual(ExampleEnum.B, nullEnum);
Assert.AreNotEqual(ExampleEnum.A, nullEnum);
}
[TestMethod]
public async Task Given_ImplicitConversion_When_Initialized_Then_Returns_Correct_Values()
{
ExampleEnum? resultA = "a";
ExampleEnum? resultB = "b";
Assert.AreEqual(ExampleEnum.A, resultA);
Assert.AreEqual(ExampleEnum.B, resultB);
}
[TestMethod]
public async Task Given_ImplicitConversion_When_Null_Then_Returns_Null()
{
ExampleEnum? input = null;
string? result = input;
Assert.IsNull(result);
}
[TestMethod]
public async Task Given_ToString_When_Called_Then_Returns_Correct_Value()
{
Assert.AreEqual("a", ExampleEnum.A.ToString());
Assert.AreEqual("b", ExampleEnum.B.ToString());
}
[TestMethod]
public async Task Given_ToString_When_Null_Then_Returns_Empty_String()
{
ExampleEnum result = ExampleEnum.FromStringOrDefault("this-is-not-a-valid-enum");
Assert.IsNull(result);
}
[TestMethod]
public async Task Given_Equals_When_ComparingCaseInsensitive_Then_Returns_True()
{
ExampleEnum result = ExampleEnum.A;
Assert.IsTrue(result.Equals(ExampleEnum.A));
Assert.IsFalse(result.Equals(ExampleEnum.B));
}
[TestMethod]
public async Task Given_FromStringOrDefault_When_InvalidString_Then_Returns_Null()
{
Assert.IsNull(ExampleEnum.FromStringOrDefault("this-is-not-a-valid-enum"));
}
[TestMethod]
public async Task Given_EqualityOperator_When_ComparingValues_Then_Returns_Correct_Values()
{
ExampleEnum target = ExampleEnum.A;
ExampleEnum otherA = ExampleEnum.A;
ExampleEnum otherB = ExampleEnum.B;
Assert.IsTrue(target == otherA);
Assert.IsFalse(target == otherB);
Assert.IsTrue(target != otherB);
Assert.IsFalse(target != otherA);
}
[TestMethod]
public async Task Given_FromStringOrDefault_When_ValidStrings_Then_Returns_Correct_Enum()
{
Assert.AreEqual(ExampleEnum.A, ExampleEnum.FromStringOrDefault("a"));
Assert.AreEqual(ExampleEnum.B, ExampleEnum.FromStringOrDefault("b"));
}
[TestMethod]
public async Task Given_ToJsonValue_When_KnownEnum_Then_Returns_String()
{
Assert.AreEqual("a", ExampleEnum.ToJsonValue(ExampleEnum.A));
Assert.AreEqual("b", ExampleEnum.ToJsonValue(ExampleEnum.B));
}
[TestMethod]
public async Task Given_ToJsonValue_When_Null_Then_Returns_Null()
{
Assert.IsNull(ExampleEnum.ToJsonValue(null));
}
[TestMethod]
public async Task Given_ToJsonValue_When_CustomEnum_Then_Returns_RawValue()
{
// After the modelInnerEnum.mustache fix, ToJsonValue preserves unknown values
// for round-trip safety instead of returning null.
ExampleEnum? custom = (ExampleEnum)"this-is-not-a-valid-enum";
Assert.AreEqual("this-is-not-a-valid-enum", ExampleEnum.ToJsonValue(custom));
}
[TestMethod]
public async Task Given_JsonSerialization_When_KnownEnum_Then_Serialize_and_Deserialize_Correctly()
{
JsonSerializerOptions options = new JsonSerializerOptions();
options.Converters.Add(new ExampleEnum.ExampleJsonConverter());
string serializedA = JsonSerializer.Serialize(ExampleEnum.A, options);
string serializedB = JsonSerializer.Serialize(ExampleEnum.B, options);
Assert.AreEqual("\"a\"", serializedA);
Assert.AreEqual("\"b\"", serializedB);
ExampleEnum? deserializedA = JsonSerializer.Deserialize<ExampleEnum>(serializedA, options);
ExampleEnum? deserializedB = JsonSerializer.Deserialize<ExampleEnum>(serializedB, options);
Assert.AreEqual(ExampleEnum.A, deserializedA);
Assert.AreEqual(ExampleEnum.B, deserializedB);
}
[TestMethod]
public async Task Given_JsonSerialization_When_EnumNotInList_Then_PreservesRawValue()
{
// After the modelInnerEnum.mustache fix, unknown values are preserved for round-trip safety.
var options = new JsonSerializerOptions();
options.Converters.Add(new ExampleEnum.ExampleJsonConverter());
ExampleEnum? value = (ExampleEnum)"not-in-list";
string serialized = JsonSerializer.Serialize(value, options);
Assert.AreEqual("\"not-in-list\"", serialized);
ExampleEnum? deserialized = JsonSerializer.Deserialize<ExampleEnum>(serialized, options);
Assert.IsNotNull(deserialized);
Assert.AreEqual("not-in-list", deserialized!.Value);
}
[TestMethod]
public async Task Given_JsonSerialization_When_Null_Value_Then_Serialize_And_Deserialize_Correctly()
{
var options = new JsonSerializerOptions();
options.Converters.Add(new ExampleEnum.ExampleJsonConverter());
ExampleEnum? value = null;
string serialized = JsonSerializer.Serialize(value, options);
Assert.AreEqual("null", serialized);
ExampleEnum? deserialized = JsonSerializer.Deserialize<ExampleEnum>("null", options);
Assert.IsNull(deserialized);
}
#region Arrange ExampleModelResponse for testing (an example) model deserialization
[TestMethod]
public async Task Given_JsonDeserialization_When_ExampleEnum_Is_Null_Then_Deserialize_Correctly_And_Not_Throw_Exception()
{
// Arrange
string json = @"
{
""exampleEnum"": null
}";
var options = new JsonSerializerOptions();
options.Converters.Add(new ExampleEnum.ExampleJsonConverter());
options.Converters.Add(new ExampleModelResponse.ExampleModelResponseJsonConverter());
// Act
ExampleModelResponse result = JsonSerializer.Deserialize<ExampleModelResponse>(json, options);
// Assert
Assert.IsNull(result.ExampleEnum);
}
[TestMethod]
public async Task Given_JsonDeserialization_When_ExampleEnum_Is_A_Then_Deserialize_Correctly_To_A()
{
// Arrange
string json = @"
{
""exampleEnum"": ""a""
}";
var options = new JsonSerializerOptions();
options.Converters.Add(new ExampleEnum.ExampleJsonConverter());
options.Converters.Add(new ExampleModelResponse.ExampleModelResponseJsonConverter());
// Act
ExampleModelResponse result = JsonSerializer.Deserialize<ExampleModelResponse>(json, options);
// Assert
Assert.AreEqual(ExampleEnum.A, result.ExampleEnum);
}
[TestMethod]
public void Given_GetHashCode_When_SameValueDifferentCase_Then_HashCodesAreEqual()
{
ExampleEnum lower = (ExampleEnum)"active";
ExampleEnum upper = (ExampleEnum)"ACTIVE";
// Equals must be true (already works)
Assert.IsTrue(lower.Equals(upper));
// GetHashCode must also be equal — this is the contract being fixed
Assert.AreEqual(lower.GetHashCode(), upper.GetHashCode());
}
[TestMethod]
public void Given_DictionaryWithEnumKey_When_LookupWithDifferentCase_Then_FindsEntry()
{
var dict = new Dictionary<ExampleEnum, string>
{
{ (ExampleEnum)"active", "found" }
};
// Before the fix this would silently return false — key not found
Assert.IsTrue(dict.ContainsKey((ExampleEnum)"ACTIVE"));
Assert.AreEqual("found", dict[(ExampleEnum)"ACTIVE"]);
}
internal class ExampleModelResponse
{
/// <summary>
/// The optional enum to test.
/// </summary>
[JsonPropertyName("exampleEnum")]
public ExampleEnum? ExampleEnum
{
get { return this._ExampleEnumOption; }
set { this._ExampleEnumOption = new(value); }
}
/// <summary>
/// Used to track if an optional field is set. If so, set the <see cref="ExampleEnum"/>.
/// </summary>
[JsonIgnore]
public Option<ExampleEnum?> _ExampleEnumOption { get; private set; }
[JsonConstructor]
public ExampleModelResponse(Option<ExampleEnum?> exampleEnum)
{
this._ExampleEnumOption = exampleEnum;
}
internal class ExampleModelResponseJsonConverter : JsonConverter<ExampleModelResponse>
{
public override ExampleModelResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions)
{
int currentDepth = utf8JsonReader.CurrentDepth;
if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray)
throw new JsonException();
JsonTokenType startingTokenType = utf8JsonReader.TokenType;
Option<ExampleEnum?> exampleEnum = default;
while (utf8JsonReader.Read())
{
if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth)
break;
if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth)
break;
if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1)
{
string? jsonPropertyName = utf8JsonReader.GetString();
utf8JsonReader.Read();
switch (jsonPropertyName)
{
case "exampleEnum":
exampleEnum = new Option<ExampleEnum?>(JsonSerializer.Deserialize<ExampleEnum?>(ref utf8JsonReader, jsonSerializerOptions));
break;
default:
break;
}
}
}
return new ExampleModelResponse(exampleEnum);
}
public override void Write(Utf8JsonWriter writer, ExampleModelResponse response, JsonSerializerOptions jsonSerializerOptions)
{
writer.WritePropertyName("exampleEnum");
JsonSerializer.Serialize(writer, response.ExampleEnum, jsonSerializerOptions);
}
}
}
#endregion
}
#region Arrange ExampleEnum for testing
[JsonConverter(typeof(ExampleJsonConverter))]
internal class ExampleEnum : IEnum
{
public string? Value { get; set; }
/// <summary>
/// ExampleEnum.A: a
/// </summary>
public static readonly ExampleEnum A = new("a");
/// <summary>
/// ExampleEnum.B: b
/// </summary>
public static readonly ExampleEnum B = new("b");
private ExampleEnum(string? value)
{
Value = value;
}
public static implicit operator ExampleEnum?(string? value) => value == null ? null : new ExampleEnum(value);
public static implicit operator string?(ExampleEnum? option) => option?.Value;
public override string ToString() => Value ?? string.Empty;
public override bool Equals(object? obj) => obj is ExampleEnum other && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase);
public override int GetHashCode() => Value != null ? StringComparer.OrdinalIgnoreCase.GetHashCode(Value) : 0;
public static bool operator ==(ExampleEnum? left, ExampleEnum? right) =>
string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase);
public static bool operator !=(ExampleEnum? left, ExampleEnum? right) =>
!string.Equals(left?.Value, right?.Value, StringComparison.OrdinalIgnoreCase);
public static ExampleEnum? FromStringOrDefault(string value)
{
return value switch {
"a" => ExampleEnum.A,
"b" => ExampleEnum.B,
_ => null,
};
}
public static string? ToJsonValue(ExampleEnum? value)
{
if (value == null)
return null;
if (value == ExampleEnum.A)
return "a";
if (value == ExampleEnum.B)
return "b";
return value.Value;
}
public class ExampleJsonConverter : JsonConverter<ExampleEnum>
{
public override ExampleEnum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions jsonOptions)
{
string str = reader.GetString();
return str == null ? null : ExampleEnum.FromStringOrDefault(str) ?? new ExampleEnum(str);
}
public override void Write(Utf8JsonWriter writer, ExampleEnum value, JsonSerializerOptions jsonOptions)
{
writer.WriteStringValue(ExampleEnum.ToJsonValue(value));
}
}
}
#endregion
}