在单元测试中从HttpResponseMessage获取响应

时间:2018-11-22 20:00:53

标签: c# asp.net-core nunit httpresponse .net-framework-version

我的控制器中有此方法,它会从数据库中查询数据,在这种情况下,它将使用提供的ID进行作业,并将HttpResponse消息发送到包含某些附件(pdf,txt等)的网站:

[HttpGet]
    [Route("jobs/{id}/attachment")]
    public HttpResponseMessage GetAttachment([FromUri]Guid id)
    {
        if (job.Blob == null)
        {
            // The job exists, but has no result data
            return this.CreateApiError(ApiError.ApiErrors.NO_CONTENT, "Job has no attachment", HttpStatusCode.NoContent);
        }

        var result = new HttpResponseMessage();
        result.Content = new StreamContent(new System.IO.MemoryStream(job.Blob));
        result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
        result.Content.Headers.ContentDisposition.FileName = job.Filename;
        result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");

        return result;
    }

它返回status 200并且工作正常。

我正在为此编写单元测试: 我模拟了作业数据,并使用JobQuery.Update(job);将其添加到数据库中 然后尝试获取它的数据:

[Test]
    public void GetAttachmentTest()
    {
        var text = Encoding.ASCII.GetBytes("{\"name\":\"John\"}");
        System.IO.File.WriteAllBytes(AppDomain.CurrentDomain.BaseDirectory + @"\" + "Report -12.txt", text);
        var job = new Job
        {
            Id = Guid.Parse("deadbeef-dead-beef-0000-000000000000"),
            Filename = "Report -12.txt",
            AudienceOrganizationId = organization.Id,
            AudienceUserId = apiUser.Id,
            Blob = text
    };

        HttpResponseMessage getAttachment;
        try
        {
            getAttachment = this.Get<HttpResponseMessage>(this.url + this.prefix + "jobs/" + job.id + "/attachment");
        }
        catch (Exception ex)
        {
            Assert.Fail("Get jobs/{id}/attachment failed");
            return;
        }
    }

this.Get<HttpResponseMessage>(this.url + this.prefix + "jobs/" + job.id + "/attachment");转到控制器,寻找具有该ID的作业,并带附件返回。 在控制器中,它工作正常,如果我查看网站的响应,我也能得到它,但是我无法在单元测试中得到它。 在getAttachment上,我得到空值。我应该如何更改单元测试以获得响应? 作业保存在数据库中。它具有我通过HttpResponse获得的附件文件。

0 个答案:

没有答案