Skip to content

Commit acbbe50

Browse files
committed
use FluentAssertions consistently in unit tests
1 parent df1df51 commit acbbe50

8 files changed

Lines changed: 184 additions & 158 deletions

File tree

src/SMAPI.Tests/Core/AssetNameTests.cs

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -56,11 +56,10 @@ public void Constructor_Valid(string name, string expectedBaseName, string? expe
5656
public void Constructor_NullOrWhitespace(string? name)
5757
{
5858
// act
59-
ArgumentException exception = Assert.Throws<ArgumentException>(() => _ = AssetName.Parse(name!, _ => null))!;
60-
61-
// assert
62-
exception.ParamName.Should().Be("rawName");
63-
exception.Message.Should().Be("The asset name can't be null or empty. (Parameter 'rawName')");
59+
FluentActions.Invoking(() => _ = AssetName.Parse(name!, _ => null)).Should()
60+
.Throw<ArgumentException>()
61+
.WithParameterName("rawName")
62+
.WithMessage("The asset name can't be null or empty. (Parameter 'rawName')");
6463
}
6564

6665

src/SMAPI.Tests/Core/ModResolverTests.cs

Lines changed: 65 additions & 67 deletions
Large diffs are not rendered by default.

src/SMAPI.Tests/Core/TranslationTests.cs

Lines changed: 27 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
using System.Diagnostics.CodeAnalysis;
44
using System.IO;
55
using System.Linq;
6+
using FluentAssertions;
67
using NUnit.Framework;
78
using StardewModdingAPI;
89
using StardewModdingAPI.Framework;
@@ -42,13 +43,12 @@ public void Helper_HandlesNoTranslations()
4243
Translation[]? translationList = helper.GetTranslations()?.ToArray();
4344

4445
// assert
45-
Assert.AreEqual("en", helper.Locale, "The locale doesn't match the input value.");
46-
Assert.AreEqual(LocalizedContentManager.LanguageCode.en, helper.LocaleEnum, "The locale enum doesn't match the input value.");
47-
Assert.IsNotNull(translationList, "The full list of translations is unexpectedly null.");
48-
Assert.AreEqual(0, translationList!.Length, "The full list of translations is unexpectedly not empty.");
46+
helper.Locale.Should().Be("en");
47+
helper.LocaleEnum.Should().Be(LocalizedContentManager.LanguageCode.en);
48+
translationList.Should().NotBeNull().And.BeEmpty();
4949

50-
Assert.IsNotNull(translation, "The translation helper unexpectedly returned a null translation.");
51-
Assert.AreEqual(this.GetPlaceholderText("key"), translation.ToString(), "The translation returned an unexpected value.");
50+
translation.Should().NotBeNull();
51+
translation.ToString().Should().Be(this.GetPlaceholderText("key"));
5252
}
5353

5454
[Test(Description = "Assert that the translation helper returns the expected translations correctly.")]
@@ -70,8 +70,9 @@ public void Helper_GetTranslations_ReturnsExpectedText()
7070
// assert
7171
foreach (string locale in expected.Keys)
7272
{
73-
Assert.IsNotNull(actual[locale], $"The translations for {locale} is unexpectedly null.");
74-
Assert.That(actual[locale], Is.EquivalentTo(expected[locale]).Using<Translation, Translation>(this.CompareEquality), $"The translations for {locale} don't match the expected values.");
73+
actual[locale].Should()
74+
.NotBeNull($"the translations for {locale} should be set")
75+
.And.BeEquivalentTo(expected[locale], $"the translations for {locale} should match the input values");
7576
}
7677
}
7778

@@ -98,8 +99,9 @@ public void Helper_Get_ReturnsExpectedText()
9899
// assert
99100
foreach (string locale in expected.Keys)
100101
{
101-
Assert.IsNotNull(actual[locale], $"The translations for {locale} is unexpectedly null.");
102-
Assert.That(actual[locale], Is.EquivalentTo(expected[locale]).Using<Translation, Translation>(this.CompareEquality), $"The translations for {locale} don't match the expected values.");
102+
actual[locale].Should()
103+
.NotBeNull($"the translations for {locale} should be set")
104+
.And.BeEquivalentTo(expected[locale], $"the translations for {locale} should match the input values");
103105
}
104106
}
105107

@@ -125,9 +127,9 @@ public void Translation_ToString([ValueSource(nameof(TranslationTests.Samples))]
125127

126128
// assert
127129
if (translation.HasValue())
128-
Assert.AreEqual(text, translation.ToString(), "The translation returned an unexpected value given a valid input.");
130+
translation.ToString().Should().Be(text, "the translation should match the valid input");
129131
else
130-
Assert.AreEqual(this.GetPlaceholderText("key"), translation.ToString(), "The translation returned an unexpected value given a null or empty input.");
132+
translation.ToString().Should().Be(this.GetPlaceholderText("key"), "the translation should match the placeholder given a null or empty input");
131133
}
132134

133135
[Test(Description = "Assert that the translation's implicit string conversion returns the expected text for various inputs.")]
@@ -138,9 +140,9 @@ public void Translation_ImplicitStringConversion([ValueSource(nameof(Translation
138140

139141
// assert
140142
if (translation.HasValue())
141-
Assert.AreEqual(text, (string?)translation, "The translation returned an unexpected value given a valid input.");
143+
((string?)translation).Should().Be(text, "the translation should match the valid input");
142144
else
143-
Assert.AreEqual(this.GetPlaceholderText("key"), (string?)translation, "The translation returned an unexpected value given a null or empty input.");
145+
((string?)translation).Should().Be(this.GetPlaceholderText("key"), "the translation should match the placeholder given a null or empty input");
144146
}
145147

146148
[Test(Description = "Assert that the translation returns the expected text given a use-placeholder setting.")]
@@ -151,11 +153,11 @@ public void Translation_UsePlaceholder([Values(true, false)] bool value, [ValueS
151153

152154
// assert
153155
if (translation.HasValue())
154-
Assert.AreEqual(text, translation.ToString(), "The translation returned an unexpected value given a valid input.");
156+
translation.ToString().Should().Be(text, "the translation should match the valid input");
155157
else if (!value)
156-
Assert.AreEqual(text, translation.ToString(), "The translation returned an unexpected value given a null or empty input with the placeholder disabled.");
158+
translation.ToString().Should().Be(text, "the translation should return the text as-is given a null or empty input with the placeholder disabled");
157159
else
158-
Assert.AreEqual(this.GetPlaceholderText("key"), translation.ToString(), "The translation returned an unexpected value given a null or empty input with the placeholder enabled.");
160+
translation.ToString().Should().Be(this.GetPlaceholderText("key"), "the translation should match the placeholder given a null or empty input with the placeholder enabled");
159161
}
160162

161163
[Test(Description = "Assert that the translation returns the expected text after setting the default.")]
@@ -166,11 +168,11 @@ public void Translation_Default([ValueSource(nameof(TranslationTests.Samples))]
166168

167169
// assert
168170
if (!string.IsNullOrEmpty(text))
169-
Assert.AreEqual(text, translation.ToString(), "The translation returned an unexpected value given a valid base text.");
171+
translation.ToString().Should().Be(text, "the translation should match the valid base text");
170172
else if (!string.IsNullOrEmpty(@default))
171-
Assert.AreEqual(@default, translation.ToString(), "The translation returned an unexpected value given a null or empty base text, but valid default.");
173+
translation.ToString().Should().Be(@default, "the translation should match the default text, given a null or empty base text and valid default.");
172174
else
173-
Assert.AreEqual(this.GetPlaceholderText("key"), translation.ToString(), "The translation returned an unexpected value given a null or empty base and default text.");
175+
translation.ToString().Should().Be(this.GetPlaceholderText("key"), translation.ToString(), "the translation should match the placeholder, given a null or empty base text and no default text");
174176
}
175177

176178
/****
@@ -211,7 +213,7 @@ public void Translation_Tokens([Values("anonymous object", "class", "IDictionary
211213
}
212214

213215
// assert
214-
Assert.AreEqual(expected, translation.ToString(), "The translation returned an unexpected text.");
216+
translation.ToString().Should().Be(expected);
215217
}
216218

217219
[Test(Description = "Assert that the translation can replace tokens in all valid formats.")]
@@ -231,7 +233,7 @@ public void Translation_Tokens_ValidFormats(string text, string key)
231233
Translation translation = new Translation("pt-BR", "key", text).Tokens(new Dictionary<string, object> { [key] = value });
232234

233235
// assert
234-
Assert.AreEqual(value, translation.ToString(), "The translation returned an unexpected value given a valid base text.");
236+
translation.ToString().Should().Be(value);
235237
}
236238

237239
[Test(Description = "Assert that translation tokens are case-insensitive and surrounding-whitespace-insensitive.")]
@@ -247,7 +249,7 @@ public void Translation_Tokens_KeysAreNormalized(string text, string key)
247249
Translation translation = new Translation("pt-BR", "key", text).Tokens(new Dictionary<string, object> { [key] = value });
248250

249251
// assert
250-
Assert.AreEqual(value, translation.ToString(), "The translation returned an unexpected value given a valid base text.");
252+
translation.ToString().Should().Be(value);
251253
}
252254

253255

@@ -261,8 +263,8 @@ public void Translation_Tokens_KeysAreNormalized(string text, string key)
261263
private void AssertSetLocale(TranslationHelper helper, string locale, LocalizedContentManager.LanguageCode localeEnum)
262264
{
263265
helper.SetLocale(locale, localeEnum);
264-
Assert.AreEqual(locale, helper.Locale, "The locale doesn't match the input value.");
265-
Assert.AreEqual(localeEnum, helper.LocaleEnum, "The locale enum doesn't match the input value.");
266+
helper.Locale.Should().Be(locale);
267+
helper.LocaleEnum.Should().Be(localeEnum);
266268
}
267269

268270
/// <summary>Get sample raw translations to input.</summary>
@@ -314,14 +316,6 @@ private IDictionary<string, Translation[]> GetExpectedTranslations()
314316
return expected;
315317
}
316318

317-
/// <summary>Get whether two translations have the same public values.</summary>
318-
/// <param name="a">The first translation to compare.</param>
319-
/// <param name="b">The second translation to compare.</param>
320-
private bool CompareEquality(Translation a, Translation b)
321-
{
322-
return a.Key == b.Key && a.ToString() == b.ToString();
323-
}
324-
325319
/// <summary>Get the default placeholder text when a translation is missing.</summary>
326320
/// <param name="key">The translation key.</param>
327321
private string GetPlaceholderText(string key)

src/SMAPI.Tests/Utilities/KeybindListTests.cs

Lines changed: 16 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using System;
22
using System.Collections.Generic;
3+
using FluentAssertions;
34
using NUnit.Framework;
45
using StardewModdingAPI;
56
using StardewModdingAPI.Utilities;
@@ -24,11 +25,10 @@ public void TryParse_SimpleValue(SButton button)
2425
bool success = KeybindList.TryParse($"{button}", out KeybindList? parsed, out string[] errors);
2526

2627
// assert
27-
Assert.IsTrue(success, "Parsing unexpectedly failed.");
28-
Assert.IsNotNull(parsed, "The parsed result should not be null.");
29-
Assert.AreEqual(parsed!.ToString(), $"{button}");
30-
Assert.IsNotNull(errors, message: "The errors should never be null.");
31-
Assert.IsEmpty(errors, message: "The input bindings incorrectly reported errors.");
28+
success.Should().BeTrue();
29+
parsed.Should().NotBeNull();
30+
parsed!.ToString().Should().Be(button.ToString());
31+
errors.Should().NotBeNull().And.BeEmpty();
3232
}
3333

3434
/// <summary>Assert the parsed fields when constructed from multi-key values.</summary>
@@ -50,10 +50,10 @@ public string TryParse_MultiValues(string? input)
5050
bool success = KeybindList.TryParse(input, out KeybindList? parsed, out string[] errors);
5151

5252
// assert
53-
Assert.IsTrue(success, "Parsing unexpectedly failed.");
54-
Assert.IsNotNull(parsed, "The parsed result should not be null.");
55-
Assert.IsNotNull(errors, message: "The errors should never be null.");
56-
Assert.IsEmpty(errors, message: "The input bindings incorrectly reported errors.");
53+
success.Should().BeTrue();
54+
parsed.Should().NotBeNull();
55+
errors.Should().NotBeNull().And.BeEmpty();
56+
5757
return parsed!.ToString();
5858
}
5959

@@ -70,10 +70,9 @@ public void TryParse_InvalidValues(string input, string expectedError)
7070
bool success = KeybindList.TryParse(input, out KeybindList? parsed, out string[] errors);
7171

7272
// assert
73-
Assert.IsFalse(success, "Parsing unexpectedly succeeded.");
74-
Assert.IsNull(parsed, "The parsed result should be null.");
75-
Assert.IsNotNull(errors, message: "The errors should never be null.");
76-
Assert.AreEqual(expectedError, string.Join("; ", errors), "The errors don't match the expected ones.");
73+
success.Should().BeFalse();
74+
parsed.Should().BeNull();
75+
errors.Should().BeEquivalentTo(errors);
7776
}
7877

7978

@@ -110,10 +109,10 @@ public SButtonState GetState(string input, string stateMap)
110109
}
111110

112111
// assert
113-
Assert.IsTrue(success, "Parsing unexpected failed");
114-
Assert.IsNotNull(parsed, "The parsed result should not be null.");
115-
Assert.IsNotNull(errors, message: "The errors should never be null.");
116-
Assert.IsEmpty(errors, message: "The input bindings incorrectly reported errors.");
112+
success.Should().BeTrue();
113+
parsed.Should().NotBeNull();
114+
errors.Should().NotBeNull().And.BeEmpty();
115+
117116
return parsed!.GetState();
118117
}
119118

src/SMAPI.Tests/Utilities/PathUtilitiesTests.cs

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using System.Diagnostics.CodeAnalysis;
22
using System.IO;
3+
using FluentAssertions;
34
using NUnit.Framework;
45
using StardewModdingAPI.Toolkit.Utilities;
56

@@ -152,7 +153,9 @@ public void GetSegments(SamplePath path)
152153
string[] segments = PathUtilities.GetSegments(path.OriginalPath);
153154

154155
// assert
155-
Assert.AreEqual(path.Segments, segments);
156+
path.Segments.Should()
157+
.HaveCount(segments.Length)
158+
.And.ContainInOrder(segments);
156159
}
157160

158161
[Test(Description = "Assert that PathUtilities.GetSegments splits paths correctly when given a limit.")]
@@ -163,7 +166,9 @@ public void GetSegments_WithLimit(SamplePath path)
163166
string[] segments = PathUtilities.GetSegments(path.OriginalPath, 3);
164167

165168
// assert
166-
Assert.AreEqual(path.SegmentsLimit3, segments);
169+
path.SegmentsLimit3.Should()
170+
.HaveCount(segments.Length)
171+
.And.ContainInOrder(segments);
167172
}
168173

169174
/****
@@ -180,7 +185,7 @@ public void NormalizeAssetName(SamplePath path)
180185
string normalized = PathUtilities.NormalizeAssetName(path.OriginalPath);
181186

182187
// assert
183-
Assert.AreEqual(path.NormalizedOnUnix, normalized); // MonoGame uses the Linux format
188+
normalized.Should().Be(path.NormalizedOnUnix); // MonoGame uses the Linux format
184189
}
185190

186191
/****
@@ -194,11 +199,13 @@ public void NormalizePath(SamplePath path)
194199
string normalized = PathUtilities.NormalizePath(path.OriginalPath);
195200

196201
// assert
202+
normalized.Should().Be(
197203
#if SMAPI_FOR_WINDOWS
198-
Assert.AreEqual(path.NormalizedOnWindows, normalized);
204+
path.NormalizedOnWindows
199205
#else
200-
Assert.AreEqual(path.NormalizedOnUnix, normalized);
206+
path.NormalizedOnUnix
201207
#endif
208+
);
202209
}
203210

204211
/****

src/SMAPI.Tests/Utilities/SDateTests.cs

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
using System.Diagnostics.CodeAnalysis;
44
using System.Linq;
55
using System.Text.RegularExpressions;
6+
using FluentAssertions;
67
using NUnit.Framework;
78
using StardewModdingAPI.Utilities;
89
using StardewValley;
@@ -67,11 +68,11 @@ public void Constructor_SetsExpectedValues([ValueSource(nameof(SDateTests.Sample
6768
SDate date = new(day, season, year);
6869

6970
// assert
70-
Assert.AreEqual(day, date.Day);
71-
Assert.AreEqual(expectedSeason, date.Season);
72-
Assert.AreEqual((int)expectedSeason, date.SeasonIndex);
73-
Assert.AreEqual(Utility.getSeasonKey(expectedSeason), date.SeasonKey);
74-
Assert.AreEqual(year, date.Year);
71+
date.Day.Should().Be(day);
72+
date.Season.Should().Be(expectedSeason);
73+
date.SeasonIndex.Should().Be((int)expectedSeason);
74+
date.SeasonKey.Should().Be(Utility.getSeasonKey(expectedSeason));
75+
date.Year.Should().Be(year);
7576
}
7677

7778
[Test(Description = "Assert that the constructor throws an exception if the values are invalid.")]
@@ -86,7 +87,9 @@ public void Constructor_SetsExpectedValues([ValueSource(nameof(SDateTests.Sample
8687
public void Constructor_RejectsInvalidValues(int day, string season, int year)
8788
{
8889
// act & assert
89-
Assert.Throws<ArgumentException>(() => _ = new SDate(day, season, year), "Constructing the invalid date didn't throw the expected exception.");
90+
FluentActions
91+
.Invoking(() => _ = new SDate(day, season, year))
92+
.Should().Throw<ArgumentException>();
9093
}
9194

9295
/****
@@ -111,7 +114,9 @@ public string FromDaysSinceStart(int daysSinceStart)
111114
public void FromDaysSinceStart_RejectsInvalidValues(int daysSinceStart)
112115
{
113116
// act & assert
114-
Assert.Throws<ArgumentException>(() => _ = SDate.FromDaysSinceStart(daysSinceStart), "Passing the invalid number of days didn't throw the expected exception.");
117+
FluentActions
118+
.Invoking(() => _ = SDate.FromDaysSinceStart(daysSinceStart))
119+
.Should().Throw<ArgumentException>();
115120
}
116121

117122
/****
@@ -241,7 +246,9 @@ public string AddDays(string dateStr, int addDays)
241246
public void AddDays_RejectsInvalidValues(string dateStr, int addDays)
242247
{
243248
// act & assert
244-
Assert.Throws<ArithmeticException>(() => _ = this.GetDate(dateStr).AddDays(addDays), "Passing the invalid number of days didn't throw the expected exception.");
249+
FluentActions
250+
.Invoking(() => _ = this.GetDate(dateStr).AddDays(addDays))
251+
.Should().Throw<ArithmeticException>();
245252
}
246253

247254

0 commit comments

Comments
 (0)