简体   繁体   中英

MockitoJunitRunner can mock a Spring @Configuration class but all fields are null

I have a Configuration class like this :

@Configuration
@ComponentScan(basePackages = "com.**.**") // production code, can't write package name
@EnableCaching
@PropertySource(value = { "classpath:application.properties", "classpath:version.txt"})
@EnableScheduling
public class AppConfig {

    @Value("${builtProfile}")
    @Nonnull
    private String activeProfile;

    ...
}

And this is the the test class :

@RunWith(MockitoJUnitRunner.class)
@ContextConfiguration(classes = {AppConfig.class, MvcConfiguration.class})
@ActiveProfiles("test")
public class NativeLoginServiceImplTest {

   @InjectMocks
   private NativeLoginServiceImpl nativeLoginServiceImpl;

   @Mock
   private AppConfig mAppConfiguration;

}

The mAppConfiguration is created during test but the problem is all of its fields are null. What wrong with my test setup and how can I make the correct one so Mockito can auto get these value in application.properties file for me?

I guess that for your fields you have at least getter methods. You should use when and thenReturn methods to make mocking work. Like this:

@Test
public void someTestMethod(){

    Mockito.when(mAppConfiguration.getActiveProfile()).thenReturn("some value");

    /** actual test goes here**/
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM