0

我正在尝试为我的一个 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>我无法做到的回报。

4

1 回答 1

1

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

使用字段、构造函数或查找方法注入将消除对 mocking 的需要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();
    }
}
于 2017-07-26T10:10:52.520 回答