[英]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: 用于实现JUnits的大多数示例代码都是从以下注释的重要性开始的:
@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. 但是,我可以运行我的测试用例(用@Test注释),而不必在类顶部使用这些注释。
What is that I have or am I missing something? 我有什么或想念什么? Will these JUnits fail in some other environment due to missing annotations?
这些JUnit在其他环境中是否会由于缺少注释而失败?
I am using @Mock and @InjectMocks annotations for Autowiring of class properties. 我正在使用@Mock和@InjectMocks注释进行类属性的自动装配。
Please assist. 请协助。
JUnit is a testing framework that is independent of Spring. JUnit是一个独立于Spring的测试框架。 This means tests by default don't use Spring.
这意味着默认情况下测试不使用Spring。
JUnit uses a Runner to run tests. JUnit使用Runner运行测试。 The class level annotation
@RunWith
tells JUnit that it should run the tests with a specific Runner
instead of the default BlockJUnit4ClassRunner. 类级别的注释
@RunWith
告诉JUnit它应该使用特定的Runner
而不是默认的BlockJUnit4ClassRunner运行测试。 For example @RunWith(SpringJUnit4ClassRunner.class)
adds additional features to JUnit that are helpful for testing Spring applications. 例如,
@RunWith(SpringJUnit4ClassRunner.class)
向JUnit添加了有助于测试Spring应用程序的附加功能。
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. 注释
@Mock
和@InjectMocks
也不是Spring的一部分。 They belong to the mocking framework Mockito . 它们属于模拟框架Mockito 。 Mockito provides three ways of using them:
Mockito提供了三种使用方式:
Add a MockitoRule to your test. 将MockitoRule添加到测试中。
public class ExampleTest {
@Mock
private YourClass something;
@InjectMocks
private AnotherClass sut;
@Rule
public final MockitoRule mockito = MockitoJUnit.rule();
@Test
public void shouldDoSomething() {
//test code
}
}
Initialize the mocks in a @Before
method with MockitoAnnotations#initMocks . 使用MockitoAnnotations#initMocks在
@Before
方法中初始化模拟 。
public class ExampleTest {
@Mock
private YourClass something;
@InjectMocks
private AnotherClass sut;
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
@Test
public void shouldDoSomething() {
//test code
}
}
Run your tests with the MockitoJUnitRunner . 使用MockitoJUnitRunner运行测试。 The runner has the disadvantage that there could only by one
Runner
and therefore you cannot combine it with another Runner
. 跑步者的缺点是只能由一个
Runner
参加,因此您不能将它与另一个Runner
结合使用。
@RunWith(MockitoJUnitRunner.StrictStubs.class)
public class ExampleTest {
@Mock
private YourClass something;
@InjectMocks
private AnotherClass sut;
@Test
public void shouldDoSomething() {
//test code
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.