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

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

问题描述

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

解决方案

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

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



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



值得注意的一件事是,通常情况下模拟对象实现与它们模拟的对象相同的接口 - 这允许您的代码通过接口类型处理它们,就像它们是实例一样真实的东西。


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

解决方案

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.

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.

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.

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天全站免登陆