coretechie
coretechie

Reputation: 1198

JUnits 4 is running without any class level annotations? What is that I am missing here?

Most of the sample codes for implementing JUnits starts with importance of following annotations:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(MockServletContext.class)

However, I am able to run my test cases (annotated with @Test) without having these annotations at the top of the class.

What is that I have or am I missing something? Will these JUnits fail in some other environment due to missing annotations?

I am using @Mock and @InjectMocks annotations for Autowiring of class properties.

Please assist.

Upvotes: 1

Views: 322

Answers (1)

Stefan Birkner
Stefan Birkner

Reputation: 24520

JUnit is a testing framework that is independent of Spring. This means tests by default don't use Spring.

JUnit uses a Runner to run tests. The class level annotation @RunWith tells JUnit that it should run the tests with a specific Runner instead of the default BlockJUnit4ClassRunner. For example @RunWith(SpringJUnit4ClassRunner.class) adds additional features to JUnit that are helpful for testing Spring applications.

For most tests you don't need a specific runner. The default runner provides enough features for most tests.

The annotations @Mock and @InjectMocks are also not part of Spring. They belong to the mocking framework Mockito. Mockito provides three ways of using them:

MockitoRule

Add a MockitoRule to your test.

public class ExampleTest {

    @Mock
    private YourClass something;

    @InjectMocks
    private AnotherClass sut;

    @Rule
    public final MockitoRule mockito = MockitoJUnit.rule();

    @Test
    public void shouldDoSomething() {
        //test code
    }
}

Explicit initialization

Initialize the mocks in a @Before method with MockitoAnnotations#initMocks.

public class ExampleTest {

    @Mock
    private YourClass something;

    @InjectMocks
    private AnotherClass sut;

    @Before
    public void initMocks() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void shouldDoSomething() {
        //test code
    }
}

MockitoJUnitRunner

Run your tests with the MockitoJUnitRunner. The runner has the disadvantage that there could only by one Runner and therefore you cannot combine it with another Runner.

@RunWith(MockitoJUnitRunner.StrictStubs.class)
public class ExampleTest {

    @Mock
    private YourClass something;

    @InjectMocks
    private AnotherClass sut;

    @Test
    public void shouldDoSomething() {
        //test code
    }
}

Upvotes: 3

Related Questions