Java模拟框架如何工作? [英] How do Java mocking frameworks work?

查看:86
本文介绍了Java模拟框架如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不是关于哪个是最好的框架等的问题。

This is NOT a question about which is the best framework, etc.

我从未使用过模拟框架,我对这个想法感到有些困惑。它是如何知道如何创建模拟对象的?它是在运行时完成还是生成文件?你怎么知道它的行为?最重要的是 - 使用这样一个框架的工作流程是什么(创建测试的步骤是什么)?

I have never used a mocking framework and I'm a bit puzzled by the idea. How does it know how to create the mock object? Is it done at runtime or does it generate a file? How do you know its behavior? And most importantly – what is the workflow of using such a framework (what is the step-by-step for creating a test)?

任何人都可以解释一下吗?你可以选择你喜欢的框架,例如说它是什么。

Can anyone explain? You can choose whichever framework you like for example, just say what it is.

推荐答案

我将谈论我使用的框架(jmock),但是其他人也做了类似的事情。

I will speak of the framework that I use ( jmock ), but others do something very similar.


它如何知道如何创建
模拟对象?

How does it know how to create the mock object?

它没有,你告诉框架你需要一个模拟对象,你给它一个对象的类型(理想情况下是一个接口)你想嘲笑。在幕后,模拟框架使用反射和有时字节码重写的组合来创建模拟对象。

It does not, you tell the framework that you require a mock object and you give it a type ( ideally an interface ) of the object that you would like to mock. Behind the scenes the mock framework uses a combination of reflection and, sometimes, byte-code rewrites to create a mock object.


是否已完成在运行时或生成
文件?

Is it done in runtime or generates a file?

jMock在运行时创建它。

jMock creates it at runtime.


你怎么知道它的行为?

How do you know its behavior?

模拟对象非常愚蠢。你指定了你期望的行为。

Mock objects are pretty dumb. You specify the behavior that you expect of them.


最重要的是 - 使用这样一个框架的
工作流程是什么
(创建
a测试的步骤是什么)。

And most importantly - what is the work flow of using such a framework (what is the step-by-step for creating a test).

一个非常重要的事情是框架必须提供能够检查在测试执行期间是否已观察到预期行为。

One very important thing that framework must provide is an ability to check that expected behavior has been observed during the test execution.

jmock通过引入特定测试运行器来检查所有已声明的所有期望测试完成后的模拟对象。如果某些内容不匹配,则抛出异常。

jmock does it by introducing specific test runner that checks that all expectations on all declared mock objects after the test has finished. If something does not match, the exception is thrown.

通常模式为:


  1. 凭空获取模拟工厂(在jmock中称为Mockery)(使用特定的无参数构造函数)。

  2. 创建所需的模拟对象。

  3. 模拟对象的设置期望

  4. 调用正在测试的方法,传递模拟而不是真实对象

  5. 如果您的方法返回一些值,请检查常规 assertXXX 方法的预期值。

  1. Acquire mock factory ( called Mockery in jmock )out of thin air ( with specific no-args constructor ).
  2. Create required mock objects.
  3. Setup expectation on mock objects
  4. Call the method you are testing, passing mocks instead of real objects
  5. If your method returns some values, check expected value with regular assertXXX methods.

这篇关于Java模拟框架如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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