0

I have a class:

classA
{
    private Boolean isEnable;

    private Config config;

    @Autowired
    private classC objC;

    public classA(Config config)
    {
        this.config = config;
        isEnable = config.getEnablingStatus();
    }

    public classB fun()
    {
        // Do something!
        // Return an object of classB!
    }
}

I want to create an object of this class in a test class, is this the right way to do it?

TestClassForClassA
{
    
    @Mock
    private classC objC;

    @Mock
    private Config config;
   
    @InjectMocks
    classA objA;

    @Before
    public void init() 
    {
        initMocks(this);
    }

    @Test
    public void testFunWhenIsEnableIsTrue()
    {
       doReturn(true).when(config).getEnablingStatus();
       objA = new classA(config);
       // The reason for above 2 lines is, I want the isEnable to be set to true in objA.
       
       // Use the objA here for the futher logic!
    }
    
    @Test
    public void testFunWhenIsEnableIsFalse()
    {
       doReturn(false).when(config).getEnablingStatus();
       objA = new classA(config);
       // The reason for above 2 lines is, I want the isEnable to be set to false in objA.
       
       // Use the objA here for the futher logic!
    }
}

My concern is, will instantiating objects of classA in the above shown way - i.e. inside different test methods, inject the objects declared as mocks (using @Mock), into it?

If not what is the right way to do it?

Aditya
  • 397
  • 2
  • 12
  • 1
    You don't need `@InjectMocks` cause you creating a real object `new classA(config)`. If you wish to test a behavior of `classA` according to mocked `config` methods - you in right way – Alex Jun 11 '21 at 09:03
  • @Alex So, as I am creating a real object I can omit the 2 objects declared as @ Mock as well right? But if I do that, can I use them in doReturn().when()...? – Aditya Jun 11 '21 at 09:11
  • If you need to inject all needed mocks without manual creation `classA` then you should use `@InjectMocks` but don't create object yourself `JUnit` will do it for you. Check this thread https://stackoverflow.com/questions/16467685/difference-between-mock-and-injectmocks – Alex Jun 11 '21 at 09:18

0 Answers0