[英]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.