【问题标题】:getBeansOfType(Class<T> type)getBeansOfType(Class<T> 类型)
【发布时间】:2018-01-01 12:34:21
【问题描述】:

我正在尝试为我的一个 API 编写 Junit,在该 API 中我使用了 Map,如下所示:

Map<String, T> beansMap = ctx.getBeansOfType(clazz);

在哪里

ctx = org.springframework.context.ApplicationContext
clazz = Class<T>

我需要模拟 ctx.getBeansOfType(clazz) 并获得此 Map&lt;Spring, T&gt; 的返回,但我无法做到。

【问题讨论】:

  • 你是如何建立 ctx 的?你能展示更多你想测试的课程吗?

标签: java spring spring-mvc junit junit5


【解决方案1】:

一般来说,直接从ApplicationContext 检索 bean 被认为是一种不好的做法,因为它引入了耦合。 看看为什么https://stackoverflow.com/a/9663099/6604329

使用字段、构造函数或查找方法注入将消除模拟 ApplicationContext 的需要。

无论如何,这里是你可以模拟ApplicationContext.getBeansOfType(clazz)的方法

import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.context.ApplicationContext;

import java.util.HashMap;
import java.util.Map;

import static org.junit.Assert.assertFalse;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
 * @author mponomarev
 */
public class ApiTest {
    @Test
    public void testSomething() throws Exception {
        ApplicationContext applicationContext = mock( ApplicationContext.class );
        final Map beans = new HashMap();

        when( applicationContext.getBeansOfType( any( Class.class ) ) )
          .thenAnswer( new Answer<Map<String,Object>>() {
              @Override
              public Map<String,Object> answer( InvocationOnMock invocation )
                throws Throwable {
                  Class clazz = invocation.getArgumentAt( 0, Class.class );
                  beans.put( "beanName", mock( clazz ) );
                  return beans;
              }
          } );

        Api api = new Api( applicationContext );
        api.perform();

        assertFalse( "beans shouldn't be empty", beans.isEmpty() );
        for( Object o : beans.values() ) {
            Component component = (Component)o;
            Mockito.verify( component ).doSomething();
        }
    }

    public static class Api {
        private final Map<String,Component> components;

        Api( ApplicationContext applicationContext ) {
            this.components = applicationContext.getBeansOfType( Component.class );
        }

        void perform() {
            for( Component component : components.values() ) {
                component.doSomething();
            }
        }
    }

    public interface Component {
        void doSomething();
    }
}

【讨论】:

  • 新手的好答案!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多