Difference between @Mock, @MockBean and Mockito.mock()

Plain Mockito library import org.mockito.Mock; … @Mock MyService myservice; and import org.mockito.Mockito; … MyService myservice = Mockito.mock(MyService.class); come from the Mockito library and are functionally equivalent. They allow to mock a class or an interface and to record and verify behaviors on it. The way using annotation is shorter, so preferable and often preferred. Note … Read more

JUnit testing with simulated user input

You can replace System.in with you own stream by calling System.setIn(InputStream in). InputStream can be a byte array: InputStream sysInBackup = System.in; // backup System.in to restore it later ByteArrayInputStream in = new ByteArrayInputStream(“My string”.getBytes()); System.setIn(in); // do your thing // optionally, reset System.in to its original System.setIn(sysInBackup); Different approach can be make this method … Read more

How to mock private method for testing using PowerMock?

I don’t see a problem here. With the following code using the Mockito API, I managed to do just that : public class CodeWithPrivateMethod { public void meaningfulPublicApi() { if (doTheGamble(“Whatever”, 1 << 3)) { throw new RuntimeException(“boom”); } } private boolean doTheGamble(String whatever, int binary) { Random random = new Random(System.nanoTime()); boolean gamble = … Read more

How to Re-run failed JUnit tests immediately?

You can do this with a TestRule. This will give you the flexibility you need. A TestRule allows you to insert logic around the test, so you would implement the retry loop: public class RetryTest { public class Retry implements TestRule { private int retryCount; public Retry(int retryCount) { this.retryCount = retryCount; } public Statement … Read more