使用NUnit对动作进行单元测试
本文关键字:单元测试 NUnit 使用 | 更新日期: 2023-09-27 18:24:54
我想用NUnit和Rhino Mocks对以下函数进行单元测试。该函数使用给定的参数创建RestSharp.RestRequest
并向dataAccessApi
:发出请求
public void CopyToUserSession(string uri, string sourcePath)
{
RestRequest request = new RestRequest(uri, Method.POST);
request.AddParameter("source-path", sourcePath);
dataAccessApi.Request<object>(request, restExecution.Get);
}
这是测试类别:
public void CopyToUserSession_ValidUriAndParameter_CallDataAccessRequest()
{
// Arrange
var dataAccessApi = MockRepository.GenerateMock<IDataAccessApi>();
var restExecution = MockRepository.GenerateMock<IRestExecution>();
var sinkNodeResource = new SinkNodeResource(dataAccessApi, restExecution);
string uri = "http://SomeUri.com";
string sourcePath = "Some Source Path";
RestRequest request = new RestRequest(uri, Method.POST);
request.AddParameter("source-path", sourcePath);
// Act
sinkNodeResource.CopyToUserSession(uri, sourcePath);
// Assert
dataAccessApi.AssertWasCalled(x => x.Request<object>(request, restExecution.Get));
}
IDataAccessApi…:
public interface IDataAccessApi
{
void Request<T>(RestRequest request, Action<T> callbackAction) where T : new();
}
以及IRestExecution:
public interface IRestExecution
{
void Get(object o);
void Put(object o);
void Post(object o);
void Delete(object o);
}
该测试使用了更容易调用的函数(如x.Test("Some String")
),但不使用Action new RestExecution().Get
——我如何对这些调用进行单元测试?
提前感谢您的帮助!
编辑:更改了关于@rich.okelly评论的代码。
编辑:添加接口的代码
尝试以下操作:
// arrange
var dataAccessApi = MockRepository.GenerateMock<IDataAccessApi>();
var restExecution = MockRepository.GenerateMock<IRestExecution>();
var sinkNodeResource = new SinkNodeResource(dataAccessApi, restExecution);
string uri = "http://SomeUri.com";
string sourcePath = "Some Source Path";
// act
sinkNodeResource.CopyToUserSession(uri, sourcePath);
// assert
dataAccessApi.AssertWasCalled(
x => x.Request<object>(
Arg<RestRequest>.Matches(
y => y.Method == Method.POST &&
y.Resource == uri &&
y.Parameters.Count == 1 &&
y.Parameters[0].Value as string == sourcePath
),
Arg<Action<object>>.Is.Equal((Action<object>)restExecution.Get)
)
);