如何在使用JPA2时对EJB进行单元测试? [英] How to unit testing EJBs when using JPA2?

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

问题描述

您如何对使用JPA的EJB进行单元测试?例如,如果我有一个Order实体和OrderEJB,它应该计算一个订单的总数(如下定义),我将如何在不触及数据库的情况下对EJB进行单元测试?另外,您将如何定义实体的值,以便断言预期的计算?以下是一些示例代码...

How would you go about unit testing an EJB that uses JPA? For example, if I have an Order entity and and OrderEJB that is supposed to calculate the total of an order (as defined below) how would I go about unit testing the EJB without touching the database? Also, how would you define values for your entities, so you can assert the expected calculation? Here is some example code below...

@Entity
public class Order {
    @Id
    private long OrderId;
    private LineItem[] items;
}

订单EJB

@Stateless
public class OrderEJB {
    EntityManager em;
    public double calculateOrderTotal(long orderId) { .. }
}

如何如果我无法触摸数据库,你会对calculateOrderTotal方法进行单元测试吗?我不想实现DAO,因为我试图摆脱这种方法。

How would you go about unit testing the calculateOrderTotal method if I can't touch the database? I don't want to implement a DAO because I'm trying to move away from that approach.

感谢您的帮助。

推荐答案

OrderEJB和Order和LineItem的一般理论(如果我们忽略注释)只是POJO,因此可以在独立的JUnit中进行测试吗?我们需要模拟EntityManager,并且可能在

Isn't the general theory that OrderEJB and Order and LineItem are (if we ignore the annotation) just POJO and therefore can be tested in stand-alone JUnit? We will need to mock EntityManager, and presumably in

 calculateOrderTotal()

你有一些概念上的代码

 em.giveMeThisOrder(orderId)

你只是嘲笑这个。您正在测试的业务逻辑然后由Mock返回的内容驱动。关键是你必须使用一个好的模拟框架,例如JMock。在任何给定的测试中,你说(显然没有这种语法):

and you just mock this. The businesss logic you're testing then gets driven by what the Mock returns. The key to this is that you must use a good mocking framework, for example JMock. In any given test you say (obviusly not with this syntax):

 EntitiyManager mockEm = // create the mock
 mockEm.check(that you are called with and order Id of 73)
 mockEm.please( when someone calls giveMeThisOrder return then **this** particular order)

因此在每次测试中,您都可以精确地创建计算代码某些方面所需的顺序。你可能有许多这样的测试可以推动计算的所有边缘和角落。

and so in each test you create exactly the order you need to exercise some aspect of your calcualtion code. You may well have many such tests that push all the edge and corner cases of your calculation.

这里的关键思想是单元测试意味着没有外部依赖,例如数据库。集成测试可以使用真正的数据库。让你的模拟正确可能很麻烦,创建那些Order实例可能会非常沉闷,但它确实会使未来的测试更快。

The key idea here is Unit Test implies no external dependency such as a Database. Integration Testing could use a real database. It can be a hassle to get your mocks right, creating those Order instances can be quite dull, but it does tend to make future testing much quicker.

我也赞成做早期的集成测试 - 你会发现另外一类错误。

I do also favour doing early integration testing - you find a whole other class of errors that way.

这篇关于如何在使用JPA2时对EJB进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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