I'm fairly new to Mockito, but can't find an answer to my question anywhere. I have a class I want to test, and need to mock a class that is an autowired field inside that test class. I'm using doReturn to try to get a method to return a certain value for the mocked class, but that method keeps returning null instead of the value. If I use Mockito.mock with SpringRunner, the mock doesn't work at all, and the method itself gets called somehow. I've been rotating between @MockBean, @Mock, and Mockito.mock, but none of them seem to work. Neither class has a constructor, and adding one will break the code.
Test class:
@RunWith(SpringRunner.class) //also tried @RunWith(MockitoJUnitRunner.class), but that failed as well
@SpringBootTest
@ExtendWith(MockitoExtension.class)
@ContextConfiguration(classes = {...})
public class testProcessorClass() {
@Autowired Cache cache; //dependency
@MockBean Comm comm; //Also tried @Mock, with @InjectMocks/initMocks
@Autowired Processor processor; //test class
@Before
public void init() {
InputObj l = new InputObj();
ReturnData r = new ReturnData();
Mockito.doReturn(r).when(comm).checkOut(l, id); id is a hardcoded id string known beforehand, both parameters are passed in correctly
}
@Test
public void testProcessorMethod() {
Request reqData = new Request(versionId, dataString);
Response response = processor.processRequest(reqData);
//response should output a JSON string that contains a key whose value is "SUCCESS", but it either outputs "ERROR" or the whole JSON string outputs {"error: "invalid input"}
}
}
Configuration:
@Configuration
public class Processor {
@Autowired Cache cache;
@Autowired Comm comm;
@Async
public Response processResponse() {
//Does a bunch of calculations, too much code to include here
ReturnData return = comm.checkOut(l, "id"); //This returns null when using @MockBeans/@Mock and returns the key "ERROR" in JSON format when using Mockito.mock, with a random string for a value
}
}
Comm class:
@Configuration
public class Comm {
//this class has no constructor, and adding one breaks the code
public ReturnData checkOut(...) {
//returns a private method that has a bug in it, which is why I'm mocking the class in the first place
}
}
I just need the checkOut method to return the JSON string I want it to return rather than returning null or some invalid JSON string. Any ideas would be appreciated.