-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathViewResultTest.cs
More file actions
73 lines (57 loc) · 2.55 KB
/
ViewResultTest.cs
File metadata and controls
73 lines (57 loc) · 2.55 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
using System;
using System.Linq.Expressions;
using System.Text.RegularExpressions;
using System.Web.Helpers;
using System.Web.Mvc;
using ExpressionToString;
namespace TestStack.FluentMVCTesting
{
public class ViewResultTest
{
private readonly ViewResultBase _viewResult;
private readonly Controller _controller;
public ViewResultTest(ViewResultBase viewResult, Controller controller)
{
_viewResult = viewResult;
_controller = controller;
}
public ModelTest<TModel> WithModel<TModel>() where TModel : class
{
if (_viewResult.Model == null)
throw new ViewResultModelAssertionException("Expected view model, but was null.");
var castedModel = _viewResult.Model as TModel;
if (castedModel == null)
throw new ViewResultModelAssertionException(string.Format("Expected view model to be of type '{0}', but it is actually of type '{1}'.", typeof(TModel).Name, _viewResult.Model.GetType().Name));
return new ModelTest<TModel>(_controller);
}
public ModelTest<TModel> WithModel<TModel>(TModel expectedModel) where TModel : class
{
var test = WithModel<TModel>();
var model = _viewResult.Model as TModel;
if (model != expectedModel)
throw new ViewResultModelAssertionException("Expected view model to be the given model, but in fact it was a different model.");
return test;
}
public ModelTest<TModel> WithModel<TModel>(Expression<Func<TModel, bool>> predicate) where TModel : class
{
var test = WithModel<TModel>();
var model = _viewResult.Model as TModel;
var modelLex = Json.Encode(model);
var predicateLex = ExpressionStringBuilder.ToString(predicate);
var compiledPredicate = predicate.Compile();
if (!compiledPredicate(model))
throw new ViewResultModelAssertionException(string.Format(
"Expected view model {0} to pass the given condition ({1}), but it failed.",
modelLex,
predicateLex));
return test;
}
public ModelTest<TModel> WithModel<TModel>(Action<TModel> assertions) where TModel : class
{
var test = WithModel<TModel>();
var model = _viewResult.Model as TModel;
assertions(model);
return test;
}
}
}