简体   繁体   中英

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?

  • Application : Spring/Hibernate
  • Junits : Spring Junit 4
  • OS : Windows 7
  • IDE : Eclipse Neon
  • Build Tool : Maven

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

Please assist.

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM