在 JUnit spring 集成中,我们可以将所有测试类扩展为一个抽象类,以便在一处实现 @Before
。
但是在 TestNG 中,由于我们必须将所有测试类扩展到 AbstractTestNGSpringContextTests
,因此我们将无法扩展到抽象类。知道如何在 Spring 的 TestNG 中使用 @BeforeMethod
、@AfterMethod
创建抽象类吗?
请提供示例。
最佳答案
这是您要找的吗?
首先构建一个类来容纳您的自定义 @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, "feedback@yoursite.com");
}
}
为了完整起见,也包括其余的类 界面
public interface EmailGenerator {
String generate();
}
具体实现
@Service
public class RandomEmailGenerator implements EmailGenerator {
@Override
public String generate() {
return "feedback@yoursite.com";
}
}
示例借自 www.mkyong.com/
关于java - TestNg + Spring Integration如何抽象beforeMethod,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39999678/