2016-10-12 3 views
0

JUnitのバネ統合では、すべてのテストクラスを抽象クラスに拡張して、@Beforeの実装を1か所に配置することができます。TestNg + Springの統合beforeMethodを抽象化する方法

しかし、TestNGでは、すべてのテストクラスをAbstractTestNGSpringContextTestsに拡張する必要があるため、抽象クラスに拡張することはできません。 SpringでTestNGに@BeforeMethod@AfterMethodという抽象クラスをどうやって作るのか?

例を示してください。

答えて

1

これはあなたが探しているものですか?

まず以下のように注釈付きメソッドをカスタム@BeforeMethodを収容するクラスを構築し、@AfterMethod:

public class LocalSpringBase extends AbstractTestNGSpringContextTests { 

    @BeforeMethod 
    public void beforeMethod() { 
     System.err.println("Another beforeMethod"); 
    } 

    @AfterMethod 
    public void afterMethod() { 
     System.err.println("Another afterMethod"); 
    } 

} 
以下に示すように

次に、あなたの実際のテストクラスがあなたのLocalSpringBaseを拡張します:

@ContextConfiguration (locations = {"classpath:spring-test-config.xml"}) 
public class TestSpring extends LocalSpringBase { 

    @Autowired 
    EmailGenerator emailGenerator; 

    @Test() 
    void testEmailGenerator() { 
     String email = emailGenerator.generate(); 
     System.out.println(email); 

     Assert.assertNotNull(email); 
     Assert.assertEquals(email, "[email protected]"); 
    } 

} 

完全性のために残りのクラスも含む インターフェイス

public interface EmailGenerator { 
    String generate(); 
} 

@Service 
public class RandomEmailGenerator implements EmailGenerator { 

    @Override 
    public String generate() { 
     return "[email protected]"; 
    } 
} 

例はwww.mkyong.com/

から借りてきた具体的な実施
関連する問題