springboot unit test specified start classes

problem

In doing unit test, to write a utility class for injecting the context of the spring.

public class AppBeanUtil implements ApplicationContextAware  {
    
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if(AppBeanUtil.applicationContext==null){
            AppBeanUtil.applicationContext = applicationContext;
        }
    }

Found vessel classes obtained by AppBeanUtil, setApplicationContext found this method does not perform.

However, when directly start the program, we found that the method can be performed.

Solution

Specifies the startup class when writing unit test classes.

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {JpaasSysApplication.class})
public class CacheUtilTest {

    @Test
    public  void  cacheTest(){
        ICache cache=CacheUtil.getCache();
        cache.set("name","ray");
        String name= (String) cache.get("name");
        System.err.println(name);

    }
}

Such injection can be automatically springboot context.

 

Guess you like

Origin www.cnblogs.com/yg_zhang/p/10937727.html