8

I'm starting on testing applications in general and I want to create several tests to learn Mockito in Spring. I've been reading several information but I have some general doubts I'd like to ask.

  1. I have seen come Mockito tests and they annotate the test of the class with: @RunWith(MockitoJUnitRunner.class) while in the Spring documentation it is used @RunWith(SpringJUnit4ClassRunner.class). I don't know what's the difference between them and which one should I use for a Spring application where tests use Mockito.
  2. As I haven't seen any real application that has test I'd like to know typical test that a developer would do. For example in a typical CRUD application for users (users can be created, updated...) can anyone a usual test that it would be done.

Thanks.

Juanillo
  • 875
  • 2
  • 11
  • 17

1 Answers1

14
@RunWith(MockitoJUnitRunner.class)

With this declaration you are suppose to write a unit test. Unit tests are exercising a single class mocking all dependencies. Typically you will inject mocked dependencies declared like this in your test case:

@Mock
private YourDependency yourDependencyMock;

@RunWith(SpringJUnit4ClassRunner.class)

Spring runner is meant for integration test (component test?) In this type of tests you are exercising a whole bunch of classes, in other words you are testing a single class with real dependencies (testing a controller with real services, DAOs, in-memory database, etc.)

You should probably have both categories in your application. Althought it is advices to have more unit tests and only few smoke integration tests, but I often found myself more confident writing almost only integration tests.

As for your second question, you should have:

  • unit tests for each class (controller, services, DAOs) separately with mocked all other classes

  • integration tests for a whole single CRUD operation. For instance creating a user that exercises controller, service, DAO and in-memory database.

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • it is a really good explanation, but sometimes, I just would like to mix unit tests and integration tests in the same test class... how do I get mockito inject functionality and spring injection? can i use to @RunWith annotaions? – Jaime Hablutzel Jun 09 '11 at 22:48
  • It's perfectly possible to mix Spring and Mockito. Basically you let Spring create and inject your mocks. See this question: http://stackoverflow.com/questions/2457239 – Tomasz Nurkiewicz Jun 10 '11 at 06:27
  • Yes, but with that approach you won't use @RunWith(MockitoJUnitRunner.class) – Jaime Hablutzel Jul 06 '11 at 03:45
  • @jaime all `@RunWith(MockitoJUnitRunner.class)`does is initialize fields of the test class annotated with `@Mock`, `@Spy`, `@Captor`, ... That initialization can also be done by calling `org.mockito.MockitoAnnotations.initMocks(this)` in the setup method of your test class. – bowmore Jan 09 '13 at 19:28