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

Mockito verify no more interactions with any mock

Since verifyNoMoreInteractions take an array of object we have to find a way to get all the created mocks. You can create this class public class MocksCollector { private final List<Object> createdMocks; public MocksCollector() { createdMocks = new LinkedList<Object>(); final MockingProgress progress = new ThreadSafeMockingProgress(); progress.setListener(new CollectCreatedMocks(createdMocks)); } public Object[] getMocks() { return createdMocks.toArray(); } … Read more

How to inject a Mock in a Spring Context [duplicate]

Yes, you are on the right track, putting a mock @Bean in a @Configuration class is one approach, and I’ll describe my experience: The trick is that you need to use a different set of .xml files purely for testing which exclude the live versions of those beans. @ContextConfiguration(locations = {“context1-test.xml”, “context2-test.xml”, …}) And the … Read more

How to handle “any other value” with Mockito?

You have two options: Matching “any value but one”, and overriding stubbing. (I suppose you could also use an Answer for complex custom behavior, but that’s overkill for situations like this one.) Stubbing any value except a given value Mockito’s AdditionalMatchers class offers a number of useful matchers, including operators such as not. This would … Read more

How to use Mockito with JUnit 5?

There are different ways to use Mockito – I’ll go through them one by one. Manually Creating mocks manually with Mockito::mock works regardless of the JUnit version (or test framework for that matter). Annotation Based Using the @Mock-annotation and the corresponding call to MockitoAnnotations::initMocks to create mocks works regardless of the JUnit version (or test … Read more

TestNG unit test not working after annotating service to test with @Retention, @Transactional, @Inherited

I recommend you to keep tests simple. You can take profit of DI benefits. For further details please visit Spring documentation: One of the major advantages of dependency injection is that it should make your code easier to unit test. You can simply instantiate objects using the new operator without even involving Spring. You can … Read more