简体   繁体   中英

Unit test to verify that variable has been changed

I'm creating a series of unit tests for an EJB application which uses JPA for the database persistence layer. As these are unit tests I'm treating the EJB beans as POJOs and using Mockito to mock the EntityManager calls.

The issue I've encountered is that one of the methods in my class under test changes a value in the entity before calling the EntityManager merge(...) method to save the entity, but I can't see how the unit test is able to check whether the method being tested did actually change the value.

Whilst I could add another when(...) method so that the merge(...) method returns an instance of the entity with the modified value, I don't think this would be of any benefit as it wouldn't actually test that the class under test had modified the value and would defeat the purpose of the test.

The method in my class under test is as follows:

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);
}

The code in my unit test is as follows:

@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 ); 
}

As the Widget class isn't being mocked I can't call something along the lines of verify(testWidget).setDiscontinued(true);

My question is how can I check whether the discontinueWidget(...) method in the class under test has actually set the discontinued variable in the Widget class to true ?

I'm using JUnit version 4.12 and Mockito version 1.10.19.

You can declare the Widget in your test as being a mock also, and verify on it.

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 ); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM