Home > Software engineering >  Java - How to Mock impl via using Mockito
Java - How to Mock impl via using Mockito

Time:05-11

I have this repository created in my class as such:

    private static ModuleRepository repository = new ModuleRepository();

its called via:

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

However when I try to mock it in my test class, I cannot actually return the mocked result I want, instead it calls the actual repository, as if my mockito call is ignored.

My Test case setup includes:

@Mock
private ModuleRepository repository;

my Test classs:

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

The actualy repository in the class isn't autowired, it's instantiated, maybe that could be it?

CodePudding user response:

Use @MockBean instead of @Mock. It tells Spring Boot that you're mocking an autowired bean.

@MockBean
private ModuleRepository repository;

Your test will also have to be annotated with @SpringBootTest

https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.testing.spring-boot-applications.mocking-beans

CodePudding user response:

If ModuleRepository is from a library you don't control, then define a Spring Bean for it as follows:

@Configuration
public class RepoConfig {
    @Bean
    public ModuleRepository getModuleRepository() {
        return new ModuleRepository();
    }
}

Now you can inject it as a Spring Bean using @Autowired, or better yet, using construction injection.

After you do this, you can use @MockBean in your test:

@MockBean
private ModuleRepository repository;

CodePudding user response:

You should initialize all of your non-bean mock objects during the test setup

  @Before
  public void setUp() {
    MockitoAnnotations.initMocks(this);
  }
  • Related