gpt4 book ai didi

java - getBeansOfType(Class 类型)

转载 作者:行者123 更新时间:2023-12-02 12:30:00 25 4
gpt4 key购买 nike

我正在尝试为我的一个 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 .

使用字段、构造函数或查找方法注入(inject)将消除模拟 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();
}
}

关于java - getBeansOfType(Class<T> 类型),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45322677/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com