How do Mockito matchers work?

Mockito matchers are static methods and calls to those methods, which stand in for arguments during calls to when and verify. Hamcrest matchers (archived version) (or Hamcrest-style matchers) are stateless, general-purpose object instances that implement Matcher<T> and expose a method matches(T) that returns true if the object matches the Matcher’s criteria. They are intended to … Read more

Using Mockito to test abstract classes

The following suggestion let’s you test abstract classes without creating a “real” subclass – the Mock is the subclass. use Mockito.mock(My.class, Mockito.CALLS_REAL_METHODS), then mock any abstract methods that are invoked. Example: public abstract class My { public Result methodUnderTest() { … } protected abstract void methodIDontCareAbout(); } public class MyTest { @Test public void shouldFailOnNullIdentifiers() … Read more

Mock HttpContext.Current in Test Init Method

HttpContext.Current returns an instance of System.Web.HttpContext, which does not extend System.Web.HttpContextBase. HttpContextBase was added later to address HttpContext being difficult to mock. The two classes are basically unrelated (HttpContextWrapper is used as an adapter between them). Fortunately, HttpContext itself is fakeable just enough for you do replace the IPrincipal (User) and IIdentity. The following code … Read more

Difference between @Mock and @InjectMocks

@Mock creates a mock. @InjectMocks creates an instance of the class and injects the mocks that are created with the @Mock (or @Spy) annotations into this instance. Note you must use @RunWith(MockitoJUnitRunner.class) or Mockito.initMocks(this) to initialize these mocks and inject them (JUnit 4). With JUnit 5, you must use @ExtendWith(MockitoExtension.class). @RunWith(MockitoJUnitRunner.class) // JUnit 4 // … Read more

What’s the difference between faking, mocking, and stubbing?

You can get some information : From Martin Fowler about Mock and Stub Fake objects actually have working implementations, but usually take some shortcut which makes them not suitable for production Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what’s programmed in for the test. … Read more