在为Controller类编写 testCase 时,私有方法是 getServiceContext()。有不同的对象,因为我们从testclass传递 serviceContext而控制器类本身的其他对象调用自身。由于这个 Foo 对象为空。如何解决这个问题。
公共类控制器{
@Refernce
private FooService fooService;
public CustomData getDetails(String id){
Foo foo = fooService.getFoo(id ,**getServiceContext()**);
//getServiceContext() is different object
System.out.println("foo data>>>> "+foo); // **Throwing null pointer exceptions**
CustomData customData = new CustomData();
customData.setStudentName(foo.getName);
customData.setStudentName(foo.getId);
...
...
...
return customData;
}
private ServiceContext getServiceContext() {
ServiceContext serviceContext = new ServiceContext();
serviceContext.setCompanyId(context..);
serviceContext.setUserId(context..);
...
....
retrn serviceContext;
}
}
公共类控制器测试{
@InjectMocks
private Controller controller;
@Mock
private FooService fooService;
private Foo foo;
@BeforeEach
public void setUp() throws PortalException {
foo = mock(Foo.class);
}
@Test
public void getDetailsTest() throws Exception {
ServiceContext **serviceContext** = new ServiceContext();
serviceContext.setCompanyId(context..);
serviceContext.setUserId(context..);
...
....
Mockito.when(fooService.getFoo("testId",serviceContext)).thenReturn(foo);
System.out.println("Service context>>>> "+**serviceContext**); // different serviceContext object
CustomData customData = controller.getDetails("testId");
Assertions.assertThat(ss).isNotNull();
}
}