我是初学者,我需要你的帮助!
我有这堂课:
public class MyClass {
private IService1 service1;
private IService2 service2;
public void setService1(final IService1 service1) {
this.service1 = service1;
}
public MyList myMethod(final Param param) throws MyException {
final MyList list = method2(param);
if (list.isEmpty()) { //here it throws a null pointer exception, because the mock didn't return "list" from my test
throw new MyException("Blablabla");
}
return list;
}
param有一个Collection myObjList,有两个list,list1和list2。
以下是method2的作用:
private MyList method2(final Param param) {
Collection<MyObj> myObjList = CollectionUtils.isEmpty(param.getMyObjList) ? list1 : list2;
MyList list = new MyList(new HashSet<>(myObjList), false);
return service1.filter(list, param);
}
我做了一个测试并模拟了service1,但是我有一个nullPointerException,我不明白为什么。
以下是测试:
@RunWith(MockitoJUnitRunner.class)
public class MyClassTest {
@InjectMocks
private MyClass myClass;
@Mock
private IService1 service1;
@Test
public void test() throws MyException {
//Given
Param param = create_param(); //this is OK
MyList list = new MyList();
list.add("something");
when(service1.filter(any(), any())).thenReturn(list); //doesn't return list
//When
MyList myObjList = myClass.method(param);
//Then
assertThat(myObjList).isNotNull();
assertThat(myObjList.size()).isEqualTo(1);
}
你能帮我理解我的错误吗?
提前致谢