Calling callbacks with Mockito

You want to set up an Answer object that does that. Have a look at the Mockito documentation, at https://static.javadoc.io/org.mockito/mockito-core/2.8.47/org/mockito/Mockito.html#answer_stubs You might write something like when(mockService.doAction(any(Request.class), any(Callback.class))).thenAnswer( new Answer<Object>() { Object answer(InvocationOnMock invocation) { ((Callback<Response>) invocation.getArguments()[1]).reply(x); return null; } }); (replacing x with whatever it ought to be, of course)

Mockito: Inject real objects into private @Autowired fields

Use @Spy annotation @RunWith(MockitoJUnitRunner.class) public class DemoTest { @Spy private SomeService service = new RealServiceImpl(); @InjectMocks private Demo demo; /* … */ } Mockito will consider all fields having @Mock or @Spy annotation as potential candidates to be injected into the instance annotated with @InjectMocks annotation. In the above case ‘RealServiceImpl’ instance will get injected … Read more

junit testing for user input using Scanner

You can change the System.in stream using System.setIn() method. Try this, @Test public void shouldTakeUserInput() { InputOutput inputOutput= new InputOutput(); String input = “add 5”; InputStream in = new ByteArrayInputStream(input.getBytes()); System.setIn(in); assertEquals(“add 5”, inputOutput.getInput()); } You have just modified the System.in field. System.in is basically an InputStream which reads from the console (hence your input … Read more

PowerMock, mock a static method, THEN call real methods on all other statics

What are you looking for is called partial mocking. In PowerMock you can use mockStaticPartial method. In PowerMockito you can use stubbing, which will stub only the method defined and leave other unchanged: PowerMockito.stub(PowerMockito.method(StaticUtilClass.class, “someStaticMethod”)).toReturn(5); also don’t forget about the @PrepareForTest(StaticUtilClass.class)

Mock final class with Mockito 2

Weird that your solution seems to work. According to their documentation on Github it says. Mocking of final classes and methods is an incubating, opt-in feature. It uses a combination of Java agent instrumentation and subclassing in order to enable mockability of these types. As this works differently to our current mechanism and this one … Read more