无法从 src/main/java 调用 src/test/java 中的代码?



我正在使用testNG编写测试用例,所有测试用例代码都在src/test/java文件夹中,现在我想在部署应用程序后从src/main/java内部的类在此文件夹中运行测试用例,可以吗?

src/main/java-> TestNGRun 下的文件

public class TestNGRun {
public static void runTestNg() {
TestListenerAdapter tla = new TestListenerAdapter();
TestNG testNG = new TestNG();
testNG.addListener(tla);
List<String> suites = new ArrayList<String>();
URL filePathUrl = TestNGRun.class.getClassLoader().getResource("/testng.xml");
suites.add(filePathUrl.getPath());
testNG.setTestSuites(suites);
testNG.run();
}
}

src/main/resources--> testng 下的文件.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Suite">
<listeners>
<listener
class-name="com.cypress.prodService.testNG.CustomisedReports"></listener>
</listeners>
<test name="ProductServiceImplTest">
<classes>
<class
name="com.cypress.prodService.testNG.ProductServiceImplTest"></class>
</classes>
</test>
</suite>

src/test/java --> ProductServiceImplTest下的文件.java

@Test
public class ProductServiceImplTest {
@Test
public void addProduct() {`enter code here`
String value="GoodMorning";
assertEquals("Hello", value);
}
}

您是否尝试过将它们放在同一个包中?这通常是您设置 JUnit 测试的方式。这是一个 JUnit5 示例,但使用 JUnit 平台启动器,通过选择包来发现测试是有效的:

https://github.com/doenn/sentences/tree/master/src https://github.com/doenn/sentences/blob/master/src/test/java/sentences/SentencesTest.java https://github.com/doenn/sentences/blob/master/src/main/java/sentences/SentenceTests.java

在testNG方面,是的也应该能够将测试放在src/test中。有关使用 testNG 的示例文件夹布局,请参阅此答案。

这可能取决于您的项目是如何设置的,但我知道对于我的所有项目,测试文件夹 IntelliJ 中的任何内容都不会允许您从主文件夹调用,只能相反。 idk 如果这是一个 Java 的东西,或者专门来自 IDE,但通常你不想在实际构建中依赖测试包中的任何内容。

补充一点,我很确定项目的测试包是专门为在正在构建的代码之外测试代码而设计的,并且在程序运行时不包含在程序的实际构建中。因此,在程序运行期间,对其中类的任何调用实际上都不会有任何要调用的内容。如果您尝试创建在程序运行时运行的某种形式的测试,我会在 src/main/中创建它,然后在那里为您的验证测试创建一个包,它们将包含在构建中。请记住,默认情况下,这些测试不会在任何 CICD 样式的构建检查中运行,因此,如果您的所有测试都在那里,您可能会得到一个错误程序,其中失败的测试通过了检查而没有失败。

最新更新