我阅读了Structuring Unit Tests,每个类都有一个测试类,每个方法都有一个内部类。想象一下,这似乎是一种组织测试的方便方法,所以我在Java项目中尝试过。但是,内部类中的测试似乎根本没有被接受。
我大致这样做了:
public class DogTests
{
public class BarkTests
{
@Test
public void quietBark_IsAtLeastAudible() { }
@Test
public void loudBark_ScaresAveragePerson() { }
}
public class EatTests
{
@Test
public void normalFood_IsEaten() { }
@Test
public void badFood_ThrowsFit() { }
}
}
JUnit不支持这个,还是我做错了?
答案 0 :(得分:75)
您应该使用@RunWith(Enclosed.class)
来宣传您的课程,并像其他人所说的那样,将内部类声明为静态:
@RunWith(Enclosed.class)
public class DogTests
{
public static class BarkTests
{
@Test
public void quietBark_IsAtLeastAudible() { }
@Test
public void loudBark_ScaresAveragePerson() { }
}
public static class EatTests
{
@Test
public void normalFood_IsEaten() { }
@Test
public void badFood_ThrowsFit() { }
}
}
答案 1 :(得分:26)
public class ServicesTest extends TestBase {
public static class TestLogon{
@Test
public void testLogonRequest() throws Exception {
//My Test Code
}
}
}
使内部类静态适用于我。
答案 2 :(得分:9)
我认为一些答案可能适用于旧版本的JUnit。在JUnit 4中,这对我有用:
@RunWith(DogTests.class)
@SuiteClasses({ DogTests.BarkTests.class, DogTests.EatTests.class })
public class DogTests extends Suite
{
public DogTests(Class<?> klass, RunnerBuilder builder) throws InitializationError {
super(klass, builder);
}
public static class BarkTests
{
@Test
public void quietBark_IsAtLeastAudible() { }
@Test
public void loudBark_ScaresAveragePerson() { }
}
public static class EatTests
{
@Test
public void normalFood_IsEaten() { }
@Test
public void badFood_ThrowsFit() { }
}
}
答案 3 :(得分:8)
我也在Nitor Creation's Nested Runner取得了成功。
添加此依赖项:
<dependency>
<groupId>com.nitorcreations</groupId>
<artifactId>junit-runners</artifactId>
<version>1.2</version>
<scope>test</scope>
</dependency>
您的考试@RunWith
:
import com.nitorcreations.junit.runners.NestedRunner
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
@RunWith(NestedRunner.class)
public class RepositoryUserServiceTest {
public class RegisterNewUserAccount {
public class WhenUserUsesSocialSignIn {
public class WhenUserAccountIsFoundWithEmailAddress {
@Test
public void shouldThrowException() {
assertTrue(true);
}
}
}
}
}
PS:示例代码已经从上面的博客文章
中获取和修改答案 4 :(得分:8)
在JUnit 5中,您只需将非静态内部类标记为@Nested
:
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
public class DogTests {
@Nested
public class BarkTests {
@Test
public void quietBark_IsAtLeastAudible() { }
@Test
public void loudBark_ScaresAveragePerson() { }
}
@Nested
public class EatTests {
@Test
public void normalFood_IsEaten() { }
@Test
public void badFood_ThrowsFit() { }
}
}