如何创建/模拟已经在Mockito单元测试中模拟过的类

watbbzwu  于 11个月前  发布在  其他
关注(0)|答案(2)|浏览(105)

我有一个类FileService,它需要运行一些单元测试。

Class FileService {
    @Autowired
    ServiceClass serviceClass;

    method_class_FileService() {
         serviceClass.method_service_class();
    }
}

Class ServiceClass {
     @Autowired
     UtilsClass utilsClass;

     method_service_class() {
           utilsClass.method();
     }
}

Class UtilsClass {
     method() {
     // Some implementation
     }
}

字符串
Mockito测试用例

@ExtendWith(MockitoExtension.class)
public class FileServiceImplTest {
     @InjectMocks
     FileService fileService;
     
     @Mock
     ServiceClass serviceClass;

     @Mock
     UtilsClass utilsClass;
     
     @Test
     public void testMethod_class_FileService() {
          when(serviceClass.method_service_class()).thenCallRealMethod();
          when(utilsClass.method_service_class()).thenCallRealMethod();
          fileService.method_class_FileService();
          //Assertions
     }
}


当调用fileService.method_class_FileService()时,它在调用utilsClass.method_service_class()时抛出NullPointerException。
试图嘲笑那些不起作用的物体。尝试使用thenCallRealMethod也不起作用。

ogq8wdun

ogq8wdun1#

将@InjectMocks替换为@Mock,以防您直接从测试用例调用服务,因为@InjectMocks使用空值模拟整个类

zd287kbt

zd287kbt2#

在搜索和阅读了一些文档之后,我明白了在进行mocks单元测试时可以只模拟直接类调用。
另外,正确的方法是只测试FileService,通过使用when(..).thenReturn(..);模拟ServiceClass,并通过创建单独的测试类(如ServiceClassTestUtilsClassTest)来测试ServiceClassUtilsClass中的其他方法,并通过Assert块中实现的值/转换来单独进行单元测试。

相关问题