getBeansOfType(Class <t> type)

时间:2017-07-26 09:21:29

标签: java spring spring-mvc junit junit5

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

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

其中

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

我需要模仿ctx.getBeansOfType(clazz)并获得此Map<Spring, T>的回复,而我无法做到这一点。

1 个答案:

答案 0 :(得分: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();
    }
}