springboot 单元测试 指定启动类

问题

在做单元测试时,写了一个工具类,用于注入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;
        }
    }

发现通过 AppBeanUtil 获取容器中的类时,发现这个setApplicationContext 方法并没有执行。

但是直接启动程序时,发现这个方法是可以执行的。

解决方法

在编写单元测试类时指定 启动类。

@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);

    }
}

这样springboot 就能够自动注入上下文。

猜你喜欢

转载自www.cnblogs.com/yg_zhang/p/10937727.html