E-Riz
E-Riz

Reputation: 33004

How to use @InjectMocks and initMocks() with an object that has a required String parameter?

Given a component to test that requires a non-mockable class (String) in it's constructor injection, like this:

public class MyService {
    @Inject
    public MyService(String param1, SomeObject param2) {
            ...
    }
}

I want to use Mockito to test it with a test harness like this:

public class MyServiceTests {
    @Mock
    private SomeObject someObject;

    @InjectMocks
    private MyService service;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }
}

Problem is, I can't @Spy or @Mock Strings (because String is a final class). So how can I use Mockito and "inject" a specific String value for the param1 argument to MyService's constructor (or otherwise test this class that requires a non-null String be passed)?

Upvotes: 38

Views: 55688

Answers (2)

Shahbaz Aamir
Shahbaz Aamir

Reputation: 327

You can try this:

@InjectMocks
private MyService service= new  MyService( param1 , param2 );

Upvotes: 3

DaveyDaveDave
DaveyDaveDave

Reputation: 10612

I think the simple answer is not to use @InjectMocks, and instead to initialise your object directly. The only downside I can see is that you're not testing the injection, but then with @InjectMocks, I think you'd be testing it with Mockito's injection implementation, rather than your real framework's implementation anyway, so no real difference.

I'd do:

public class MyServiceTests {
  @Mock
  private SomeObject someObject;

  private MyService service;

  @Before
  public void setUp() {
    service = new MyService("foo", someObject);
  }
}

Upvotes: 45

Related Questions