JUnit:@之前只针对一些测试方法?

u2nhd7ah  于 2023-01-26  发布在  其他
关注(0)|答案(6)|浏览(171)

我有一些常用的设置代码,我已经将它们分解成一个标记为@Before的方法。但是,没有必要为每个测试运行所有这些代码。是否有一种方法可以标记它,以便@Before方法只在某些测试之前运行?

h5qlskok

h5qlskok1#

只需将不需要设置代码的测试移到一个单独的测试类中,如果您有一些其他测试通用的代码,这将有助于保留,将其移到一个helper类中。

lrpiutwd

lrpiutwd2#

@嵌套+ @每个之前

完全同意将相关代码移到内部类的观点。下面是我所做的。
1.在测试类中创建内部类
1.使用@Nested注解内部类
1.移动要在内部类中使用的所有测试方法
1.在内部类中编写init代码,并使用@BeforeEach对其进行注解
下面是代码:

class Testing {

    @Test
    public void testextmethod1() {
    
      System.out.println("test ext method 1");
    
    }
    
    @Nested
    class TestNest{
    
       @BeforeEach
       public void init() {
          System.out.println("Init");
       }
    
       @Test
       public void testmethod1() {
          System.out.println("This is method 1");
       }
    
       @Test
       public void testmethod2() {
          System.out.println("This is method 2");
       }
    
       @Test
       public void testmethod3() {
          System.out.println("This is method 3");
       }
        
     }

     @Test
     public void testextmethod2() {
    
         System.out.println("test ext method 2");
    
     }

}

以下是输出

test ext method 1
test ext method 2
Init
This is method 1
Init
This is method 2
Init
This is method 3

注意:我不确定Junit 4是否支持此操作,但我在JUnit 5中支持此操作

flmtquvp

flmtquvp3#

也可以从JUnit通过Assume实现,然后你可以检查你想要处理@Before的方法名。

public class MyTest {
     @Rule
     public TestName testName = new TestName();

     @Before
     public void setUp() {
       assumeTrue(testName.getMethodName().equals("myMethodName"));
       // setup follows
     }
}

查看topic,了解有关@Rule的更多信息。

k2fxgqgv

k2fxgqgv4#

现在是2023年,我建议继续使用JUnit5.x
我还要说这可能是一个微优化,我不会去努力,直到我衡量我的测试时间,看到运行代码时,不必要的增加了大量的时间。

0wi1tuuw

0wi1tuuw5#

不确定@Before,但我最近想出了一个策略,让@After块有选择地运行。实现是直接的。作为测试类的一部分,我将一些标志设置为默认值。它们在@Before类中被重置为默认值。在类中,我需要做一些特定于标志的事情,我在@After中设置了这些标志&我检查标志值来完成相应的工作。

7bsow1i6

7bsow1i66#

JUnit 4.12提供封闭的运行程序,如

@RunWith(Enclosed.class) 
public class GlobalTest{

    @RunWith(MockitoJUnitRunner.class)
    public class InnerTest{
    
    }

}

相关问题