• [翻译]使用自定义IHttpBody类扩展Web测试


    如果您已经录制了一个Web测试并生成了代码,您可能已经注意到了FormPostHttpBody 类。您甚至还可能看到StringHttpBody 类如果在您的Web测试中存在Web服务请求。只有两个内置的类用于生成 HTTP 请求正文,所以如果您要发送请求除了包含某些窗体参数和字符串以外的,您只需实现自己的 IHttpBody 类。

    我将粘贴一个叫做BinaryHttpBody的IHttpBody示例在这之后。这个类可以用于编码的Web测试中发送请求体中特定的二进制数据请求。例如,如果你想在一个PUT请求体中发送二进制数据你可以使用这个类。如果您希望从磁盘上的文件加载预生成请求正文是另一种用法。正如您看到,BinaryHttpBody 的构造函数接受一个字节数组或一个流。

    要发送一串字节,您可以这样使用BinaryHttpBody :

    WebTestRequest request1 = new WebTestRequest("http://localhost/test.aspx");
    request1.Method = "POST"
    BinaryHttpBody binaryBody = new BinaryHttpBody("application/octet-stream",
    new byte[] { 0x01, 0x02, 0x03 });
    request1.Body = binaryBody;
    yield return request1;

    以下BinaryHttpBody代码将要兼容7月的CTP版和其之后的版本。

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Text;
    using Microsoft.VisualStudio.TestTools.WebTesting;
    
    namespace TestProject1 {
        public class BinaryHttpBody : IHttpBody {
            private string _contentType;
            private Stream _stream;
    
            public BinaryHttpBody(string contentType, byte[] bytes)
                : this(contentType, new MemoryStream(bytes, false)) {
    
            }
    
            public BinaryHttpBody(string contentType, Stream stream) {
                _contentType = contentType;
                _stream = stream;
            }
    
            public BinaryHttpBody() {
    
            }
    
            public string ContentType {
                get { return _contentType; }
                set { _contentType = value; }
            }
    
            public Stream Stream {
                get { return _stream; }
                set { _stream = value; }
            }
    
            public void WriteHttpBody(WebTestRequest request, System.IO.Stream bodyStream) {
                if (_stream != null && _stream.CanRead) {
                    try {
                        byte[] buffer = new byte[8192];
                        int bytesRead;
                        while ((bytesRead = _stream.Read(buffer, 0, buffer.Length)) > 0) {
                            bodyStream.Write(buffer, 0, bytesRead);
                        }
                    } finally {
                        _stream.Close();
                    }
                }
            }
    
            public object Clone() {
                throw new NotImplementedException();
            }
        }
    }
    这仅是Web测试提供的一个可扩展性的一个例子。我计划接下来演示自定义的验证和提取规则。
               JoshCh发布于星期三,2005年8月24日下午1点14
    原文地址:http://blogs.msdn.com/joshch/archive/2005/08/24/45...

    OscarXie.net

    关注质量与体验——电子商务与自动化测试
    http://www.cnblogs.com/oscarxie/

  • 相关阅读:
    expect 函数体 花括号
    bash 连接字符串
    Ubuntu下搭建Python开发环境
    expect
    >&2
    expect语法基础: while、for 循环、if 语句的用法示例
    bash exit
    python开发工具
    eclipse中安装adt出现了duplicate location错误怎样解决
    shell source
  • 原文地址:https://www.cnblogs.com/oscarxie/p/945706.html
Copyright © 2020-2023  润新知