-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathControllerActionTester.cs
297 lines (263 loc) · 12.2 KB
/
ControllerActionTester.cs
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
using System;
using System.Linq;
using System.Web.Mvc;
namespace SparkyTestHelpers.AspNetMvc
{
/// <summary>
/// Helper for testing ASP.NET MVC controller actions.
/// </summary>
public class ControllerActionTester
{
private readonly Func<ActionResult> _controllerAction;
private IModelTester _modelTester;
private string _expectedViewName = null;
private bool _expectedViewNameSpecified;
/// <summary>
/// The <see cref="Controller" /> instance being tested.
/// </summary>
public Controller Controller { get; private set; }
/// <summary>
/// Called by the
/// <see cref="ControllerTester{TController}.Action(System.Linq.Expressions.Expression{Func{TController, Func{ActionResult}}})"/>
/// method.
/// </summary>
/// <param name="controller">The "parent" <see cref="System.Web.Mvc.Controller"/>.</param>
/// <param name="controllerAction">"Callback" function that privides the controller action to be tested.</param>
internal ControllerActionTester(Controller controller, Func<ActionResult> controllerAction)
{
Controller = controller;
_controllerAction = controllerAction;
}
/// <summary>
/// "Callback" action to "arrange" the test.
/// </summary>
/// <returns>"This" <see cref="ControllerActionTester"/>.</returns>
public ControllerActionTester When(Action action)
{
action?.Invoke();
return this;
}
/// <summary>
/// Sets up ModelState.IsValid value.
/// </summary>
/// <returns>"This" <see cref="ControllerActionTester"/>.</returns>
public ControllerActionTester WhenModelStateIsValidEquals(bool isValid)
{
SetModelStateIsValid(isValid);
return this;
}
/// <summary>
/// Specifies that the
/// <see cref="TestView(Action{ViewResult})"/> and
/// <see cref="TestPartialView(Action{PartialViewResult})"/> methods should throw an exception
/// if the action result's .ViewName doesn't match the <paramref name="expectedViewName"/>.
/// </summary>
/// <param name="expectedViewName">The expected view name.</param>
/// <returns>"This" <see cref="ControllerActionTester"/>.</returns>
public ControllerActionTester ExpectingViewName(string expectedViewName)
{
_expectedViewName = expectedViewName;
_expectedViewNameSpecified = true;
return this;
}
/// <summary>
/// Specifies that the
/// <see cref="TestView(Action{ViewResult})"/> or
/// <see cref="TestJson(Action{JsonResult})"/> method should throw an exception
/// if the action result's .Model or .Data type doesn't match <typeparamref name="TModelType"/>.
/// </summary>
/// <typeparam name="TModelType">The expected model type.</typeparam>
/// <param name="validate">(Optional) callback action to preform additional model validation.</param>
/// <returns>"This" <see cref="ControllerActionTester"/>.</returns>
public ControllerActionTester ExpectingModel<TModelType>(Action<TModelType> validate = null)
{
_modelTester = new ModelTester<TModelType>(validate);
return this;
}
/// <summary>
/// Tests that controller action returns a <see cref="ContentResult"/>.
/// </summary>
/// <param name="validate">(Optional) callback validation function.</param>
/// <returns>The <see cref="ContentResult"/> returned from the controller action.</returns>
public ContentResult TestContent(Action<ContentResult> validate = null)
{
return TestResult<ContentResult>(result =>
{
validate?.Invoke(result);
});
}
/// <summary>
/// Tests that controller action returns a <see cref="EmptyResult"/>.
/// </summary>
/// <param name="validate">(Optional) callback validation function.</param>
/// <returns>The <see cref="EmptyResult"/> returned from the controller action.</returns>
public EmptyResult TestEmpty(Action<EmptyResult> validate = null)
{
return TestResult<EmptyResult>(result =>
{
validate?.Invoke(result);
});
}
/// <summary>
/// Tests that controller action returns a <see cref="FileResult"/>.
/// </summary>
/// <param name="validate">(Optional) callback validation function.</param>
/// <returns>The <see cref="FileResult"/> returned from the controller action.</returns>
public FileResult TestFile(Action<FileResult> validate = null)
{
return TestResult<FileResult>(result =>
{
validate?.Invoke(result);
});
}
/// <summary>
/// Tests that controller action returns a <see cref="JsonResult"/>.
/// </summary>
/// <param name="validate">(Optional) callback validation function.</param>
/// <returns>The <see cref="JsonResult"/> returned from the controller action.</returns>
public JsonResult TestJson(Action<JsonResult> validate = null)
{
return TestResult<JsonResult>(result =>
{
_modelTester?.Test(result.Data);
validate?.Invoke(result);
});
}
/// <summary>
/// Test that controller action returns a <see cref="PartialViewResult"/>.
/// </summary>
/// <param name="validate">(Optional) callback validation function.</param>
/// <returns>The <see cref="PartialViewResult"/> returned from the controller action.</returns>
public PartialViewResult TestPartialView(Action<PartialViewResult> validate = null)
{
return TestResult<PartialViewResult>(result =>
{
AssertViewName(_expectedViewName, result.ViewName);
_modelTester?.Test(result.Model);
validate?.Invoke(result);
});
}
/// <summary>
/// Tests that controller action returns a <see cref="RedirectResult"/>.
/// </summary>
/// <param name="expectedUrl">The expected URL.</param>
/// <param name="validate">(Optional) callback validation function.</param>
/// <returns>The <see cref="FileResult"/> returned from the controller action.</returns>
public RedirectResult TestRedirect(string expectedUrl, Action<RedirectResult> validate = null)
{
return TestResult<RedirectResult>(result =>
{
string actual = result.Url;
if (!string.Equals(expectedUrl, actual, StringComparison.InvariantCulture))
{
throw new ControllerTestException($"Expected Url <{expectedUrl}>. Actual: <{actual}>.");
}
validate?.Invoke(result);
});
}
/// <summary>
/// Tests that controller action redirects to the specified action name.
/// </summary>
/// <param name="expectedActionName">The expected action name.</param>
/// <param name="validate">(Optional) callback validation action.</param>
/// <returns>The <see cref="RedirectToActionResult"/> returned from the controller action.</returns>
public RedirectToRouteResult TestRedirectToAction(
string expectedActionName, Action<RedirectToRouteResult> validate = null)
{
const string key = "action";
return TestResult<RedirectToRouteResult>(result =>
{
if (!result.RouteValues.ContainsKey(key))
{
throw new ControllerTestException($"RouteValues dictionary does not contain \"{key}\" value.");
}
string actual = result.RouteValues[key].ToString();
if (!string.Equals(expectedActionName, actual, StringComparison.InvariantCulture))
{
throw new ControllerTestException($"Expected action name <{expectedActionName}>. Actual: <{actual}>.");
}
validate?.Invoke(result);
});
}
/// <summary>
/// Tests that controller action redirects to the specified route.
/// </summary>
/// <param name="expectedRoute">The expected route.</param>
/// <param name="validate">(Optional) callback validation function.</param>
/// <returns>The <see cref="RedirectToRouteResult"/> returned from the controller action.</returns>
public RedirectToRouteResult TestRedirectToRoute(
string expectedRoute, Action<RedirectToRouteResult> validate = null)
{
return TestResult<RedirectToRouteResult>(result =>
{
string actual = string.Join("/", result.RouteValues.Values.Select(v => v.ToString()));
if (!string.Equals(expectedRoute, actual, StringComparison.InvariantCulture))
{
throw new ControllerTestException($"Expected route <{expectedRoute}>. Actual: <{actual}>.");
}
validate?.Invoke(result);
});
}
/// <summary>
/// Test the result of the controller action.
/// </summary>
/// <typeparam name="TActionResultType">The expected <see cref="ActionResult"/>
/// type that should be returned from the action.</typeparam>
/// <param name="validate">(Optional) callback validation action.</param>
/// <returns>The <typeparamref name="TActionResultType"/> returned from the controller action.</returns>
/// <exception cref="ControllerTestException">if any errors are asserted.</exception>
public TActionResultType TestResult<TActionResultType>(Action<TActionResultType> validate = null)
where TActionResultType : ActionResult
{
TActionResultType actionResult = AssertActionResultType<TActionResultType>(_controllerAction());
validate?.Invoke(actionResult);
return actionResult;
}
/// <summary>
/// Tests that controller action returns a <see cref="ViewResult"/>.
/// </summary>
/// <param name="validate">(Optional) callback validation function.</param>
/// <returns>The <see cref="ViewResult"/> returned from the controller action.</returns>
public ViewResult TestView(Action<ViewResult> validate = null)
{
return TestResult<ViewResult>(result =>
{
AssertViewName(_expectedViewName, result.ViewName);
_modelTester?.Test(result.Model);
validate?.Invoke(result);
});
}
private TActionResultType AssertActionResultType<TActionResultType>(ActionResult actionResult)
where TActionResultType : ActionResult
{
Type expectedType = typeof(TActionResultType);
if (actionResult == null || !TypeTester.IsOfType(actionResult, expectedType))
{
string actualTypeName = (actionResult == null) ? "null" : actionResult.GetType().FullName;
throw new ControllerTestException(
$"Expected ActionResult type {expectedType.FullName}. Actual: {actualTypeName}.");
}
return (TActionResultType)actionResult;
}
private void AssertViewName(string expectedViewName, string actualViewName)
{
if (_expectedViewNameSpecified)
{
string expected = expectedViewName ?? string.Empty;
string actual = actualViewName ?? string.Empty;
if (!string.Equals(expected, actual, StringComparison.InvariantCulture))
{
throw new ControllerTestException($"Expected ViewName <{expected}>. Actual: <{actual}>.");
}
}
}
private void SetModelStateIsValid(bool isValid = true)
{
Controller.ModelState.Clear();
if (!isValid)
{
Controller.ModelState.AddModelError("key", "message");
}
}
}
}