【发布时间】:2016-01-12 11:19:48
【问题描述】:
所以我开始为我们的 Java-Spring 项目编写测试。
我使用的是 JUnit 和 Mockito。据说,当我使用 when()...thenReturn() 选项时,我可以模拟服务,而无需模拟它们左右。所以我想做的是,设置:
when(classIwantToTest.object.get().methodWhichReturnsAList(input))thenReturn(ListcreatedInsideTheTestClass)
但是无论我使用哪个 when 子句,我总是会得到一个 NullpointerException,这当然是有道理的,因为输入为空。
当我尝试从一个对象模拟另一个方法时:
when(object.method()).thenReturn(true)
我还得到了一个 Nullpointer,因为该方法需要一个未设置的变量。
但我想使用 when()..thenReturn() 来绕过创建这个变量等等。我只是想确定,如果任何类调用了这个方法,那么无论如何,只要返回 true 或上面的列表。
这基本上是我的误解,还是有其他问题?
代码:
public class classIWantToTest implements classIWantToTestFacade{
@Autowired
private SomeService myService;
@Override
public Optional<OutputData> getInformations(final InputData inputData) {
final Optional<OutputData> data = myService.getListWithData(inputData);
if (data.isPresent()) {
final List<ItemData> allData = data.get().getItemDatas();
//do something with the data and allData
return data;
}
return Optional.absent();
}
}
这是我的测试课:
public class Test {
private InputData inputdata;
private ClassUnderTest classUnderTest;
final List<ItemData> allData = new ArrayList<ItemData>();
@Mock
private DeliveryItemData item1;
@Mock
private DeliveryItemData item2;
@Mock
private SomeService myService;
@Before
public void setUp() throws Exception {
classUnderTest = new ClassUnderTest();
myService = mock(myService.class);
classUnderTest.setService(myService);
item1 = mock(DeliveryItemData.class);
item2 = mock(DeliveryItemData.class);
}
@Test
public void test_sort() {
createData();
when(myService.getListWithData(inputdata).get().getItemDatas());
when(item1.hasSomething()).thenReturn(true);
when(item2.hasSomething()).thenReturn(false);
}
public void createData() {
item1.setSomeValue("val");
item2.setSomeOtherValue("test");
item2.setSomeValue("val");
item2.setSomeOtherValue("value");
allData.add(item1);
allData.add(item2);
}
【问题讨论】:
-
when() 中的对象必须是由 Mockito.mock() 创建的模拟,它不适用于手动创建的真实对象 - 不确定这是否是您的问题,因为我并没有真正了解你的问题出在哪里……
-
请贴一些代码。
-
听起来
classIwantToTest.object.get()结果不是模拟,或者get()返回 null。但请发布您的代码,展示您的测试和模拟的初始化。 -
添加了一些代码。需要更改变量名,因为它来自我的公司;)。
-
在下面参考我的答案
标签: java testing junit mockito stubbing