我知道如何使用这些术语,但我想知道单元测试是否有伪造、模拟和存根的公认定义?如何为您的测试定义这些?描述一下你可能会用到它们的场景。

以下是我如何使用它们:

Fake:实现接口但包含固定数据且没有逻辑的类。只是根据实现返回“好”或“坏”数据。

Mock:实现接口的类,允许从特定方法动态设置返回值/抛出异常,并提供检查特定方法是否被调用/未调用的能力。

Stub:类似于模拟类,只是它不提供验证方法是否被调用的能力。

模拟和存根可以手工生成,也可以由模拟框架生成。假类是手工生成的。我使用模拟主要是为了验证我的类和依赖类之间的交互。一旦我验证了交互并在代码中测试替代路径,我就使用存根。我使用伪类主要是为了抽象出数据依赖关系,或者当mock /存根太乏味而每次都无法设置时。


当前回答

为了说明存根和模拟的用法,我还想包括一个基于Roy Osherove的“单元测试的艺术”的例子。

想象一下,我们有一个LogAnalyzer应用程序,它的唯一功能是打印日志。它不仅需要与web服务对话,而且如果web服务抛出错误,LogAnalyzer必须将错误记录到不同的外部依赖项,通过电子邮件发送给web服务管理员。

下面是我们想要在LogAnalyzer中测试的逻辑:

if(fileName.Length<8)
{
 try
  {
    service.LogError("Filename too short:" + fileName);
  }
 catch (Exception e)
  {
    email.SendEmail("a","subject",e.Message);
  }
}

当web服务抛出异常时,如何测试LogAnalyzer正确地调用电子邮件服务? 以下是我们面临的问题:

我们如何替换web服务? 我们如何模拟来自web服务的异常,以便我们可以 测试对电子邮件服务的调用? 我们如何知道电子邮件服务是否被正确调用 所有的吗?

我们可以通过使用web服务的存根来处理前两个问题。为了解决第三个问题,我们可以为电子邮件服务使用一个模拟对象。

A fake is a generic term that can be used to describe either a stub or a mock.In our test, we’ll have two fakes. One will be the email service mock, which we’ll use to verify that the correct parameters were sent to the email service. The other will be a stub that we’ll use to simulate an exception thrown from the web service. It’s a stub because we won’t be using the web service fake to verify the test result, only to make sure the test runs correctly. The email service is a mock because we’ll assert against it that it was called correctly.

[TestFixture]
public class LogAnalyzer2Tests
{
[Test]
 public void Analyze_WebServiceThrows_SendsEmail()
 {
   StubService stubService = new StubService();
   stubService.ToThrow= new Exception("fake exception");
   MockEmailService mockEmail = new MockEmailService();

   LogAnalyzer2 log = new LogAnalyzer2();
   log.Service = stubService
   log.Email=mockEmail;
   string tooShortFileName="abc.ext";
   log.Analyze(tooShortFileName);

   Assert.AreEqual("a",mockEmail.To); //MOCKING USED
   Assert.AreEqual("fake exception",mockEmail.Body); //MOCKING USED
   Assert.AreEqual("subject",mockEmail.Subject);
 }
}

其他回答

存根——为方法调用提供预定义答案的对象。

Mock -一个你设定期望的对象。

假的——一个功能有限的对象(用于测试),例如一个假的web服务。

Test Double是存根、mock和fake的总称。但非正式地,你会经常听到人们简单地称之为mock。

这是一个让测试富有表现力的问题。如果我想让测试描述两个对象之间的关系,我就在Mock上设置期望。我存根返回值,如果我设置一个支持对象,让我在测试中有趣的行为。

为了说明存根和模拟的用法,我还想包括一个基于Roy Osherove的“单元测试的艺术”的例子。

想象一下,我们有一个LogAnalyzer应用程序,它的唯一功能是打印日志。它不仅需要与web服务对话,而且如果web服务抛出错误,LogAnalyzer必须将错误记录到不同的外部依赖项,通过电子邮件发送给web服务管理员。

下面是我们想要在LogAnalyzer中测试的逻辑:

if(fileName.Length<8)
{
 try
  {
    service.LogError("Filename too short:" + fileName);
  }
 catch (Exception e)
  {
    email.SendEmail("a","subject",e.Message);
  }
}

当web服务抛出异常时,如何测试LogAnalyzer正确地调用电子邮件服务? 以下是我们面临的问题:

我们如何替换web服务? 我们如何模拟来自web服务的异常,以便我们可以 测试对电子邮件服务的调用? 我们如何知道电子邮件服务是否被正确调用 所有的吗?

我们可以通过使用web服务的存根来处理前两个问题。为了解决第三个问题,我们可以为电子邮件服务使用一个模拟对象。

A fake is a generic term that can be used to describe either a stub or a mock.In our test, we’ll have two fakes. One will be the email service mock, which we’ll use to verify that the correct parameters were sent to the email service. The other will be a stub that we’ll use to simulate an exception thrown from the web service. It’s a stub because we won’t be using the web service fake to verify the test result, only to make sure the test runs correctly. The email service is a mock because we’ll assert against it that it was called correctly.

[TestFixture]
public class LogAnalyzer2Tests
{
[Test]
 public void Analyze_WebServiceThrows_SendsEmail()
 {
   StubService stubService = new StubService();
   stubService.ToThrow= new Exception("fake exception");
   MockEmailService mockEmail = new MockEmailService();

   LogAnalyzer2 log = new LogAnalyzer2();
   log.Service = stubService
   log.Email=mockEmail;
   string tooShortFileName="abc.ext";
   log.Analyze(tooShortFileName);

   Assert.AreEqual("a",mockEmail.To); //MOCKING USED
   Assert.AreEqual("fake exception",mockEmail.Body); //MOCKING USED
   Assert.AreEqual("subject",mockEmail.Subject);
 }
}

我倾向于使用两个术语-假和Mock。

只有在使用像Moq这样的Mock框架时才使用Mock,因为当它使用new Mock<ISomething>()创建时,将其称为Fake似乎是不正确的-虽然从技术上讲,您可以使用Mock框架创建stub或Fakes,但在这种情况下这样称呼它似乎有点愚蠢-它必须是Mock。

其他都是假的。如果一个Fake可以被总结为一个功能降低的实现,那么我认为一个Stub也可以是一个Fake(如果不是,谁在乎呢,每个人都知道我的意思,而且从来没有人说过“我认为你会发现那是一个Stub”)

Stub和fake是对象,因为它们可以根据输入参数改变响应。它们之间的主要区别是Fake比存根更接近真实世界的实现。存根基本上包含对预期请求的硬编码响应。让我们看一个例子:

public class MyUnitTest {

 @Test
 public void testConcatenate() {
  StubDependency stubDependency = new StubDependency();
  int result = stubDependency.toNumber("one", "two");
  assertEquals("onetwo", result);
 }
}

public class StubDependency() {
 public int toNumber(string param) {
  if (param == “one”) {
   return 1;
  }
  if (param == “two”) {
   return 2;
  }
 }
}

A mock is a step up from fakes and stubs. Mocks provide the same functionality as stubs but are more complex. They can have rules defined for them that dictate in what order methods on their API must be called. Most mocks can track how many times a method was called and can react based on that information. Mocks generally know the context of each call and can react differently in different situations. Because of this, mocks require some knowledge of the class they are mocking. a stub generally cannot track how many times a method was called or in what order a sequence of methods was called. A mock looks like:

public class MockADependency {

 private int ShouldCallTwice;
 private boolean ShouldCallAtEnd;
 private boolean ShouldCallFirst;

 public int StringToInteger(String s) {
  if (s == "abc") {
   return 1;
  }
  if (s == "xyz") {
   return 2;
  }
  return 0;
 }

 public void ShouldCallFirst() {
  if ((ShouldCallTwice > 0) || ShouldCallAtEnd)
   throw new AssertionException("ShouldCallFirst not first thod called");
  ShouldCallFirst = true;
 }

 public int ShouldCallTwice(string s) {
  if (!ShouldCallFirst)
   throw new AssertionException("ShouldCallTwice called before ShouldCallFirst");
  if (ShouldCallAtEnd)
   throw new AssertionException("ShouldCallTwice called after ShouldCallAtEnd");
  if (ShouldCallTwice >= 2)
   throw new AssertionException("ShouldCallTwice called more than twice");
  ShouldCallTwice++;
  return StringToInteger(s);
 }

 public void ShouldCallAtEnd() {
  if (!ShouldCallFirst)
   throw new AssertionException("ShouldCallAtEnd called before ShouldCallFirst");
  if (ShouldCallTwice != 2) throw new AssertionException("ShouldCallTwice not called twice");
  ShouldCallAtEnd = true;
 }

}