Java 中的模拟对象是什么? [英] What are mock objects in Java?

查看:31
本文介绍了Java 中的模拟对象是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道 Java 中的模拟对象是什么.我们为什么要创建它们以及它们的用途是什么?

I like to know what mock objects are in Java. Why do we create them and what are their uses?

推荐答案

Mock 对象是用于单元测试的东西.如果您有一个要测试其方法的对象,并且这些方法依赖于某个其他对象,则您可以创建依赖项的模拟,而不是该依赖项的实际实例.这允许您单独测试您的对象.

A Mock object is something used for unit testing. If you have an object whose methods you want to test, and those methods depend on some other object, you create a mock of the dependency rather than an actual instance of that dependency. This allows you to test your object in isolation.

用于创建模拟对象的常见 Java 框架包括 JMockEasyMock.它们通常允许您创建可以定义其行为的模拟对象,因此当您在模拟对象上调用方法时,您可以确切地知道会发生什么(就返回值和副作用而言).

Common Java frameworks for creating mock objects include JMock and EasyMock. They generally allow you to create mock objects whose behavior you can define, so you know exactly what to expect (as far as return values and side effects) when you call methods on the mock object.

举个例子,一个常见的用例可能是在 MVC 应用程序中,其中有一个 DAO 层(数据访问对象)和一个执行业务逻辑的控制器.如果您想对控制器进行单元测试,并且控制器依赖于 DAO,您可以对 DAO 进行模拟,将虚拟对象返回给您的控制器.

As an example, one common use case might be in an MVC application, where you have a DAO layer (data access objects) and a Controller that performs business logic. If you'd like to unit test the controller, and the controller has a dependency on a DAO, you can make a mock of the DAO that will return dummy objects to your controller.

需要注意的重要一点是,通常情况下,mock 对象实现与它们正在模拟的对象相同的接口 - 这允许您的代码通过接口类型处理它们,就好像它们是真实的东西.

One thing thats important to note is that its usually the case that mock objects implement the same interface as the objects that they are mocking - this allows your code to deal with them via the interface type, as if they are instances of the real thing.

这篇关于Java 中的模拟对象是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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