1

I have a java class whose constructor looks like this

    private SomeManager someManager;

    public MyService() {
       this.someManager = ManagerHandler.getDefault();
    }

The issue is that while testing ManagerHandler is not initialised so I am not able to create new object of this class to test its method. I am using mockito for testing. I am not able to understand How to mock a parameter which I am not passing in the constructor.

Is there anyway I can mock someManager using PowerMock?

thatman
  • 333
  • 3
  • 14
  • Note that its `public`, not `Public`. – Zabuzard Jul 20 '21 at 16:14
  • Does this answer your question? [Mocking static methods with Mockito](https://stackoverflow.com/questions/21105403/mocking-static-methods-with-mockito) – talex Jul 20 '21 at 16:32
  • 1
    Design your classes in such a way that they become testable, e.g. by using dependency injection: `public MyService(SomeManager manager) { this.someManager = manager; }` then initialize `new MyService(ManagerHandler.getDefault());` – knittl Jul 20 '21 at 16:36

1 Answers1

1

You can use InjectMocks annotation. See below example:

MyService class:

public class MyService {
    ManagerHandler someManager;

    public MyService() {
        this.someManager = ManagerHandler.getDefault();
    }

    // other methods
    public String greetUser(String user) {
        return someManager.sayHello(user) + ", Good Morning!";
    }
}

ManagerHandler class:

public class ManagerHandler {
    public static ManagerHandler getDefault() {
        return new ManagerHandler();
    }

    public String sayHello(String userName) {
        return "Hello " + userName;
    }
}

TestClass:

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class TestClass {
    @Mock
    ManagerHandler someManager;

    @InjectMocks
    MyService myService = new MyService();

    @Test
    public void test() {
        //mock methods of ManagerHandler
        Mockito.when(someManager.sayHello("Alice")).thenReturn("Hello Alice");

        assertEquals("Hello Alice, Good Morning!", myService.greetUser("Alice"));
    }
}
pcsutar
  • 1,715
  • 2
  • 9
  • 14