[英]JUnits 4 is running without any class level annotations? What is that I am missing here?
用于实现JUnits的大多数示例代码都是从以下注释的重要性开始的:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(MockServletContext.class)
但是,我可以运行我的测试用例(用@Test注释),而不必在类顶部使用这些注释。
我有什么或想念什么? 这些JUnit在其他环境中是否会由于缺少注释而失败?
我正在使用@Mock和@InjectMocks注释进行类属性的自动装配。
请协助。
JUnit是一个独立于Spring的测试框架。 这意味着默认情况下测试不使用Spring。
JUnit使用Runner运行测试。 类级别的注释@RunWith
告诉JUnit它应该使用特定的Runner
而不是默认的BlockJUnit4ClassRunner运行测试。 例如, @RunWith(SpringJUnit4ClassRunner.class)
向JUnit添加了有助于测试Spring应用程序的附加功能。
对于大多数测试,您不需要特定的跑步者。 默认运行程序为大多数测试提供了足够的功能。
注释@Mock
和@InjectMocks
也不是Spring的一部分。 它们属于模拟框架Mockito 。 Mockito提供了三种使用方式:
将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
}
}
使用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
}
}
使用MockitoJUnitRunner运行测试。 跑步者的缺点是只能由一个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.