如何最好地对 Web 应用程序进行单元测试 [英] How to best do unit testing for a web application

查看:26
本文介绍了如何最好地对 Web 应用程序进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个在 UI 方面非常复杂的 Web 应用程序,并且严重依赖 AJAX、DOM 和图像操作.

I am writing a web application that is very complex in terms of UI and relies heavily on AJAX, DOM and image manipulations.

是否有任何标准做法(我不需要工具)可以用来减少错误?

Is there any standard practice (I don't want tools) which can be followed to reduce the bugs?

推荐答案

将逻辑部分和 UI 部分分开 - 不要将所有业务逻辑和复杂代码放在页面背后的代码中.而是在标准层结构(数据层、业务规则/逻辑层、UI 层)之外构建它们.这将确保您要测试的逻辑代码不会引用表单,而是使用易于单元测试的类.

Separate the logic and the UI portions - do not have all your business logic and complex code in the code behind page. Instead build them off the standard tier structure (data layer, business rules / logic layer, UI layer). This will ensure that your logic code you want to test does not reference the form, but instead uses classes that are easily unit tested.

对于一个非常基本的示例,没有执行此操作的代码:

For a very basic example, don't have code that does this:

string str = TextBox1.Text.ToString();
//do whatever your code does
TextBox2.Text = str;

改为使用方法将逻辑提取到单独的类中:

Instead extract the logic into a separate class with a method:

TextBox2.Text = DoWork(TextBox1.Text.ToString());

public class Work
{
    public string DoWork(string str)
    {
      //do work
      return str2;
    }
}

通过这种方式,您可以编写单元测试来验证 DoWork 是否返回正确的值:

This way you can write unit tests to verify that DoWork is returning the correct values:

string return = DoWork("TestThisString");

现在您的所有逻辑都可以进行单元测试,只有在您的 UI 层中必须直接引用页面的代码.

Now all of your logic is unit testable, with only code that HAS to reference the page directly still in your UI layer.

这篇关于如何最好地对 Web 应用程序进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆