如何使用DUnit测试私有方法? [英] How can I test private methods with DUnit?

查看:180
本文介绍了如何使用DUnit测试私有方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,我使用DUnit进行单元测试。
它有一些方法一些公共方法和私有方法。

 键入
TAuth = class TDataModule)
private
procedure PrivateMethod;
public
procedure PublicMethod;
结束

为了为这个类写一个单元测试,我必须使所有的方法公开。 p>

是否有不同的方法来声明私有方法,以便我仍然可以测试它们但不公开?

解决方案

你不需要让它们公开。受保护的会做。然后,您可以对类进行单元测试的子类型,并表示受保护的方法。例如:

  type 
TAuth = class(TDataModule)
protected
procedure MethodIWantToUnitTest;
public
procedure PublicMethod;
结束

现在您可以将其子类型进行单元测试:

 界面

使用
TestFramework,Classes,AuthDM;

类型
//类TAuthDM的测试方法
TestAuthDM =类(TTestCase)
// stuff
end;

TAuthDMTester = class(TAuthDM)
public
procedure MethodIWantToUnitTestMadePublic;
结束

实现

程序TAuthDMTester.MethodIWantToUnitTestMadePublic;
begin
MethodIWantToUnitTest;
结束

但是,如果要单元测试的方法与数据模块密切相关,除了私有的东西以外,它们是不安全的,那么你应该考虑重构这些方法,以便隔离需要进行单元测试的代码和访问数据模块内部的代码。


I have a class that I am unit testing into with DUnit. It has a number of methods some public methods and private methods.

type
  TAuth = class(TDataModule)
  private
    procedure PrivateMethod;
  public
    procedure PublicMethod;
  end;

In order to write a unit test for this class I have to make all the methods public.

Is there a different way to declare the private methods so that I can still test them but they are not public?

解决方案

You don't need to make them public. Protected will do. Then you can subtype the class for unit testing and surface the protected methods. Example:

type
  TAuth = class(TDataModule)
  protected
    procedure MethodIWantToUnitTest;
  public
    procedure PublicMethod;
  end;

Now you can subtype it for your unit test:

interface

uses
  TestFramework, Classes, AuthDM;

type
  // Test methods for class TAuthDM
  TestAuthDM = class(TTestCase)
     // stuff
  end;

  TAuthDMTester = class(TAuthDM)
  public
    procedure MethodIWantToUnitTestMadePublic;
  end;

implementation

procedure TAuthDMTester.MethodIWantToUnitTestMadePublic;
begin
  MethodIWantToUnitTest;
end;

However, if the methods you want to unit test are doing things so intimately with the data module that it is not safe to have them anything but private, then you should really consider refactoring the methods in order to segregate the code which needs to be unit tested and the code which accesses the innards of the data module.

这篇关于如何使用DUnit测试私有方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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