java - getBeansOfType(Class<T> type) -
i trying write junit 1 of api, within api have used map below:
map<string, t> beansmap = ctx.getbeansoftype(clazz); where
ctx = org.springframework.context.applicationcontext clazz = class<t> i need mock ctx.getbeansoftype(clazz) , return of map<spring, t> not able it.
in general it's considered bad practice retrieve beans directly applicationcontext, it's introduces coupling. see why https://stackoverflow.com/a/9663099/6604329.
using field, constructor or lookup-method injection eliminate need mocking applicationcontext.
any way, here how can mock 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 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(); } }
Comments
Post a Comment