简体   繁体   中英

Creating instances of different class types in a function

While building a unit test, I'm struggling with the correct way of trying to achieve the follow: I'd like to have a function that receives Varargs of Class, and will have the ability to instantiate each of the given classes. It's something like this:

    public static void mockContextBeans(Class<?>... classes) throws Exception{
      for (Class<?> c : classes){
          when(context.getBean(c)).thenReturn(c.newInstance());
      }
    }

Can someone please point me to the correct way achieving it?

Thanks

You're fighting against the way Spring is supposed to be used, but if you really need to make that work you probably could say ....thenReturn(Mockito.mock(c)) . Mockito shouldn't care what kinds of constructors exist on the classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM