0

I have a spring based (no springboot) application inside which I have a class as below:

 public class MyClass {
    
     private static final ApplicationContext context = new AnnotationConfigApplicationContext(AppContext.class);
     
    MyClass (){
     //get the beans from the applicationcontext that myClass is dependent on
    }
    
    //class methods
    
    }
    

I am trying to unit test MyClass class , but I am unable to mock the context that is loaded here -

 private static final ApplicationContext context = new 
       AnnotationConfigApplicationContext(AppContext.class);

Please help me here!!!

  • You cannot mock a variable which is assigned by creating a new instance by using the `new` keyword. Use a DI framework (like Spring) and inject the instance. Then you can mock it from your tests. Or use something like Powermock – Thiyagu Nov 28 '21 at 13:04
  • Hi @user7 Can you elaborate by giving me an example? – Shridha Jalihal Nov 28 '21 at 13:05
  • Note: using powermock is not recommended. See [Why not PowerMock](https://stackoverflow.com/questions/30162200/why-not-powermock) – Thiyagu Nov 28 '21 at 13:07
  • ok I am somehow realizing that I am not following good programming principles :( – Shridha Jalihal Nov 28 '21 at 13:13

0 Answers0