簡體   English   中英

單元測試以驗證變量是否已更改

[英]Unit test to verify that variable has been changed

我正在為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);我無法調用verify(testWidget).setDiscontinued(true);verify(testWidget).setDiscontinued(true);

我的問題是如何檢查被測試類中的discontinueWidget(...)方法是否實際上將Widget類中的discontinued變量設置為true

我正在使用JUnit版本4.12和Mockito版本1.10.19。

您可以將測試中的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 ); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM