Java -如何通过使用Mockito来模拟实现

wz1wpwve  于 2022-11-08  发布在  Java
关注(0)|答案(4)|浏览(280)

我在我的类中创建了这样的存储库:

  1. private static ModuleRepository repository = new ModuleRepository();

通过以下方式调用:

  1. repository.isModuleCached(moduleType,taxModuleInfo.getModuleYear(), taxModuleInfo.getModuleVersion()

然而,当我试图在我的测试类中模拟它时,我实际上不能返回我想要的模拟结果,而是它调用实际的存储库,就好像我的mockito调用被忽略了一样。
我的测试用例设置包括:

  1. @Mock
  2. private ModuleRepository repository;

我的测试类:

  1. when(repository.isModuleCached(anyString(), anyString(), anyString())).thenReturn(resp);

类中的实际存储库不是自动连接的,它是示例化的,可能是这样吧?

cig3rfwq

cig3rfwq1#

使用@MockBean而不是@Mock。它告诉SpringBoot您正在模拟一个自动连接的bean。

  1. @MockBean
  2. private ModuleRepository repository;

您的测试还必须使用@SpringBootTest进行注解
https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.testing.spring-boot-applications.mocking-beans

dced5bon

dced5bon2#

如果ModuleRepository来自您不控制的库,则为其定义一个Spring Bean,如下所示:

  1. @Configuration
  2. public class RepoConfig {
  3. @Bean
  4. public ModuleRepository getModuleRepository() {
  5. return new ModuleRepository();
  6. }
  7. }

现在,您可以使用@Autowired将其作为SpringBean注入,或者更好的是,使用构造注入。
完成此操作后,您可以在测试中使用@MockBean

  1. @MockBean
  2. private ModuleRepository repository;
chy5wohz

chy5wohz3#

您应该在测试设置过程中初始化所有非bean模拟对象

  1. @Before
  2. public void setUp() {
  3. MockitoAnnotations.initMocks(this);
  4. }
idv4meu8

idv4meu84#

避免when(xxx.xxx()).thenReturn(xxx)
请改用doReturn(xxx).when(xxx).xxx()
下面是一个示例:doReturn(resp).when(repository).isModuleCached(anyString(), anyString(), anyString());
此外,不会注入存储库值。private static ModuleRepository repository = new ModuleRepository();
因为您是手动初始化变数,所以您必须使用Reflection,手动以Mock对象取代它。
Spring提供了ReflectionTestUtils,这将会有所帮助。

相关问题