您好,我有一个窗口服务项目,该项目已经成功实现到服务器上。但是我必须创建单元测试,我坚持了数周才能解决它。你们可以帮我吗?
我已经清理了几次该项目,而当我尝试根据自己的界面设置Mock时出现了问题
我也多次重构了代码,但是无法运行 unittest:(
这是我的代码:
界面
public interface IJobScheduler
{
Task<HttpResponseMessage> GetASync(HttpClient client, string destination, CancellationTokenSource cancelToken);
Task<bool> RunJobAgent(HttpClient client);
}
类 (故意创建以使用单元测试注入数据)
public class JobSchedular
{
private IJobScheduler iJobScheduler;
public JobSchedular(IJobScheduler ijobscheduler) => iJobScheduler = ijobscheduler;
public JobSchedular() => iJobScheduler = new JobSchedularSvc();
public async Task<HttpResponseMessage> GetASync(HttpClient client, string destination, CancellationTokenSource cancelToken)
{
Task<HttpResponseMessage> result = iJobScheduler.GetASync(client, destination, cancelToken);
return await result;
}
}
实际课程
public partial class JobSchedularSvc : ServiceBase, IJobScheduler
{
public async Task<HttpResponseMessage> GetASync(HttpClient client, string destination, CancellationTokenSource cancelToken)
{
try
{
HttpResponseMessage response;// = new HttpResponseMessage();
using (client)
{
response = await client.GetAsync(destination, cancelToken.Token);
}
return response;
}
catch (Exception ex)
{
LogHandler.InsertLog(LogLevel.Error, $"FAILED: GetAsync() - {ex.Message}", ex.StackTrace, "JobSchedulerSvc", "JobSchedulerSvc", null, null, null, null).Wait();
return null;
}
}
}
测试方法
public async Task Test()
{
var message = new HttpResponseMessage(HttpStatusCode.OK);
JobScheduler = new Mock<IJobScheduler>();
JobScheduler.Setup(test => test.GetASync(It.IsAny<HttpClient>(), It.IsAny<string>(), It.IsAny<CancellationTokenSource>()))
.Returns(Task.FromResult(new HttpResponseMessage() { StatusCode = HttpStatusCode.OK, Content = new StringContent("{'Result':true,'Exception':[]}") }));
CancellationTokenSource cancelToken = new CancellationTokenSource();
var response = new JobSchedular(JobScheduler.Object).GetASync(new HttpClient(), "/api/job/runjobagent", cancelToken);
var result = await response.Result.Content.ReadAsStringAsync();
Assert.AreEqual(result, "{'Result':true,'Exception':[]}");
}
我只想调用返回httpResponseMessage的本地函数GetAsync()
答案 0 :(得分:0)
我编辑.csproj文件并添加此行,
<PropertyGroup>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
</PropertyGroup>