使用 JUnit 的内部类中的测试用例

我阅读了关于 结构化单元测试的内容,每个类有一个测试类,每个方法有一个内部类。我想这似乎是组织测试的一种方便的方法,所以我在我们的 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 不支持这个吗,还是我做错了?

50025 次浏览
public class ServicesTest extends TestBase {


public static class TestLogon{


@Test
public void testLogonRequest() throws Exception {
//My Test Code
}
}
}

Making the inner class static works for me.

You should annontate your class with @RunWith(Enclosed.class), and like others said, declare the inner classes as static:

@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() { }
}
}

I think some of the answers might be for older versions of JUnit. In JUnit 4 this worked for me:

    @RunWith(Suite.class)
@Suite.SuiteClasses({ DogTests.BarkTests.class, DogTests.EatTests.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() { }
}
}

I've had success with Nitor Creation's Nested Runner as well.

How to use Nitor Creation's Nested Runner

There is a post explaining it here:

Add this dependency:

<dependency>
<groupId>com.nitorcreations</groupId>
<artifactId>junit-runners</artifactId>
<version>1.2</version>
<scope>test</scope>
</dependency>

And a @RunWith to your test:

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: The example code has been taken and modified from the above blog post

In JUnit 5, you simply mark non-static inner classes as @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() { }
}
}