单元测试以验证变量是否已更改

时间:2015-09-20 12:34:28

标签: java unit-testing jpa junit mockito

我为EJB应用程序创建了一系列单元测试,它将JPA用于数据库持久层。由于这些是单元测试,我将EJB bean视为POJO并使用Mockito来模拟EntityManager调用。

我遇到的问题是我的测试类中的一个方法在调用EntityManager merge(...)方法之前更改了实体中的值以保存实体,但我不能看看单元测试如何能够检查被测试的方法是否确实改变了值。

虽然我可以添加另一个when(...)方法,以便merge(...)方法返回具有修改值的实体实例,但我不认为这会带来任何好处,因为它不会实际上,测试被测试的类已经修改了这个值,并且会破坏测试的目的。

我所测试的课程中的方法如下:

public void discontinueWidget(String widgetId) {
    Widget widget = em.find(Widget.class, widgetId);
    //Code that checks whether the widget exists has been omitted for simplicity
    widget.setDiscontinued(true);
    em.merge(widget);
}

我的单元测试中的代码如下:

@Mock
private EntityManager em;

@InjectMocks
private WidgetService classUnderTest;

@Test
public void discontinueWidget() {
    Widget testWidget = new Widget();
    testWidget.setWidgetName("foo");
    when(em.find(Widget.class, "foo")).thenReturn(testWidget);

    classUnderTest.discontinueWidget("en");

    //something needed here to check whether testWidget was set to discontinued

    //this checks the merge method was called but not whether the
    //discontinued value has been set to true
    verify(em).merge(testWidget ); 
}

由于Widget类没有被嘲笑,我无法按照verify(testWidget).setDiscontinued(true);

的方式调用某些内容

我的问题是如何检查被测试类中的discontinueWidget(...)方法是否实际上将discontinued类中的Widget变量设置为true

我使用的是JUnit版本4.12和Mockito版本1.10.19。

1 个答案:

答案 0 :(得分:4)

您可以将测试中的Widget声明为模拟,并在其上进行验证。

Widget testWidget = mock(Widget.class);
when(em.find(Widget.class, "foo")).thenReturn(testWidget);

classUnderTest.discontinueWidget("en");

//something needed here to check whether testWidget was set to discontinued
verify(testWidget).setDiscontinued(true);  

//this checks the merge method was called but not whether the
//discontinued value has been set to true
verify(em).merge(testWidget ); 
相关问题