是否可以使用junit和mockito创建嵌套单元测试?
例如:
@RunWith(MockitoJUnitRunner.class)
public class ClientFormServiceTest {
@Mock
ClientFormService clientFormService;
public class GetNewClientFormTest {
@Mock
protected ClientForm result;
@Before
public void given() {
result = clientFormService.getNewForm();
}
@Test
public void should_do_something() {
}
}
public class CreateClientFormTest {
@Mock
protected ClientForm clientForm;
@Before
public void given() {
clientFormService.createForm(clientForm);
}
@Test
public void should_do_something() {
}
}
}
这就是我想要做的,但如果嵌套到类中,我无法运行单元测试。
For example:
@RunWith(MockitoJUnitRunner.class)
public class ClientFormServiceTest {
@Mock
ClientFormService clientFormService;
public class GetNewClientFormTest {
@Mock
protected ClientForm result;
@Before
public void given() {
result = clientFormService.getNewForm();
}
@Test
public void should_do_something() {
}
}
public class CreateClientFormTest {
@Mock
protected ClientForm clientForm;
@Before
public void given() {
clientFormService.createForm(clientForm);
}
@Test
public void should_do_something() {
}
}
}
This is what I want to do but I can't run the unit tests if are nested to a class.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我是 JUnit TestRunner junit-nested 的作者,我相信它可以满足您的需求: https: //github.com/avh4/junit-nested
但是,从您的示例来看,尚不清楚为什么需要嵌套测试。使用它们的典型原因是共享设置行为,但您应该考虑使用单独的测试类是否更合适。
无论如何,以下是如何使用 junit-nested 做到这一点:(由于
Nested
是一个测试运行器,因此您必须使用MockitoAnnotations.initMocks()
而不是Mockito 测试运行程序。)I'm the author of a JUnit TestRunner, junit-nested, which I believe may do what you want: https://github.com/avh4/junit-nested
However, from your example it's not clear why you need nested tests. The typical reason to use them is to share setup behavior, but you should consider if having separate test classes is more appropriate.
In any case, here's how you can do it with junit-nested: (Since
Nested
is a test runner, you'll have to useMockitoAnnotations.initMocks()
instead of the Mockito test runner.)你为什么要这么做?如果您想从许多类似测试中的代码重用中受益,您可以提出一个具有公共代码的基本测试类,并让测试类扩展它。
Why would you like to do that? If you mean to benefit from code reuse among many similar tests, you could come up with a base test class with common code and make test classes extend it.