【问题标题】:Unit test to verify that variable has been changed单元测试以验证变量是否已更改
【发布时间】:2015-09-20 12:34:28
【问题描述】:

我正在为使用 JPA 作为数据库持久层的 EJB 应用程序创建一系列单元测试。由于这些是单元测试,我将 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(...) 方法是否实际上将Widget 类中的discontinued 变量设置为true

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

【问题讨论】:

    标签: java unit-testing jpa junit mockito


    【解决方案1】:

    您也可以在测试中将 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 ); 
    

    【讨论】:

      猜你喜欢
      • 2017-03-22
      • 2011-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-05
      • 2018-08-31
      • 2018-12-18
      相关资源
      最近更新 更多