我想测试一下这个控制器:
[HttpGet]
public IList<Notification> GetNotificationsByCustomerAndId([FromUri] string[] name, [FromUri] int[] lastNotificationID)
{
return _storage.GetNotifications(name, lastNotificationID, _topX);
}
特别是,在这个方法中,我想测试传入输入以形成请求Url的数组是否与进入routeData.Values
的数组相同。如果对于单值参数(不是数组),它可以工作,但不能用于数组。如果我调试Values
,我只看到controller
和action
。
[TestMethod]
public void GetNotificationsByCustomerAndId_ArrayOverload_Should_Match_InputParameter_name()
{
string[] _testName = new string[] { _testCustomer, _testCustomerBis };
string Url = string.Format(
"http://www.testpincopallo.it/Notifications/GetByCustomerAndLastID/customersNotificationsInfos?name={0}&name={1}&lastNotificationID={2}&lastNotificationID={3}",
_testName[0], _testName[1],
_testNotificationID, _testNotificationIDBis);
IHttpRouteData routeData = GetRouteData(Url);
routeData.Values["name"].Should().Be(_testName);
}
当你传递数组的时候,有没有其他的方法来进行单元测试?
发布于 2015-12-16 01:22:16
我认为你应该创建一个新的方法,它将自动确定数组元素的数量,并将它们暴露给url。
private static void ParameterSubstitution(string[] testName, string[] testNotification, ref string url)
{
const string firstParametrName = "name";
const string secondParametrName = "lastNotificationID";
// first parametr
url += string.Format("?{0}={1}", firstParametrName, string.Join(string.Format("&{0}=", firstParametrName), testName));
// second parametr
url += string.Format("&{0}={1}", secondParametrName, string.Join(string.Format("&{0}=",secondParametrName), testNotification));
}
然后你可以像这样使用它:
var testName = new[] { "Name1", "Name2"};
var testNotification = new[] { "Notification1", "Notification2", "Notification3" };
var Url =
@"http://www.testpincopallo.it/Notifications/GetByCustomerAndLastID/customersNotificationsInfos";
ParameterSubstitution(testName, testNotification, ref Url);
发布于 2015-12-16 03:07:47
您可以创建数组项的查询字符串参数列表,然后使用&作为分隔符的String.Join方法连接它们。这样就可以很容易地得到所需的查询字符串。
[TestMethod]
public void GetNotificationsByCustomerAndId_ArrayOverload_Should_Match_InputParameter_name()
{
string[] _testName = new string[] { _testCustomer, _testCustomerBis };
// ASSUMING _testNotificationIDBis IS STRING ARRAY
List<string> nParams = _testName.Select(n => string.Format("lastNotificationID={0}", n)).ToList<string>();
string Url = string.Format(
"http://www.testpincopallo.it/Notifications/GetByCustomerAndLastID/customersNotificationsInfos?name={0}&name={1}&{2}",
_testName[0], _testName[1],
String.Join("&", nParams.ToArray()));
IHttpRouteData routeData = GetRouteData(Url);
routeData.Values["name"].Should().Be(_testName);
}
https://stackoverflow.com/questions/34038494
复制相似问题