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

For a component that requires a non -oxidable class ( String) to check it, the embedding of the constructor in it, for example:

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

I want to use Mockito for testing with a test harness as follows:

public class MyServiceTests {
    @Mock
    private SomeObject someObject;

    @InjectMocks
    private MyService service;

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

The problem is that I cannot @Spyor @MockStrings (because it Stringis the final class). So, how can I use Mockito and β€œinsert” a specific String value for an argument param1into the constructor MyService(or else test this class for which you want to pass a non-empty String)?

+4
source share
1 answer

, @InjectMocks, , . , , , , @InjectMocks, , Mockito, , .

:

public class MyServiceTests {
  @Mock
  private SomeObject someObject;

  private MyService service;

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

Source: https://habr.com/ru/post/1623998/


All Articles