0

For example, i have such class:

         class Foo {
          public String xMethod() {
              Ent ent = y.callExternalMethod();
              if(ent.equals("")){
              ...
              }
               ...
          }

And a test class:

class FooTest {
   
@Mock
Ent ent = new Ent(someData);

@InjectMocks
Foo f;

public void checkFooWithMock() {
  ...
}
}

I need to use mocked ent instance in this case, how can i do that?

dan k
  • 41
  • 6
  • 1
    You need to mock y – tgdavies Jul 25 '23 at 07:15
  • 1
    If `y` is created in the class `Foo` using `new` operator, you stop doing that and pass it in the constructor instead. It's called "dependency injection". Google the words in the quotes to know more. – Abhijit Sarkar Jul 25 '23 at 07:16
  • y is a private field in Foo class and do not being created by new keyword. – dan k Jul 25 '23 at 07:20
  • @dank Then the suggested solution still applies. Pass your `y` as a parameter in your `Foo` constructor, so you can pass in a mock during test, then have `y.callExternalMethod()` return your `Ent` mock. – Jorn Jul 25 '23 at 07:29
  • You need to show more of your code: where does y come from? – tgdavies Jul 25 '23 at 08:18
  • i finally did it: created y object as a spy, then added Mockito.doReturn(neededValue).when(y).callExternalMethod. Thanks for attempts to help) – dan k Jul 25 '23 at 11:12
  • 1
    `@Mock Ent ent = new Ent(someData);` is redundant. You can either assign a value or you can use the `@Mock` annotation. You cannot do both and it will confuse `@InjectMocks`; also see [Why are my mocked methods not called when executing a unit test?](https://stackoverflow.com/q/74027324/112968) for more insights and a several solutions how to implement "dependency injection". (I'm not VTC as dupe, because this question is different, but still very similar (or is it?)) – knittl Jul 25 '23 at 19:59

0 Answers0