我正在尝试为我的一种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>的返回。

最佳答案

通常,直接从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();
    }
}

07-24 15:05