java - 如何从 Maven 项目中的自定义 jar 运行测试?
问题描述
我创建了带有存储库 (MyRepo)、模型 (MyClass) 和一些测试 (MyTests) 的自定义 jar。
这是我的自定义 jar 中的测试类:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = MyApp.class)
public class MyTests{
private MockMvc mockMvc;
@Autowired
private WebApplicationContext context;
@Autowired
private MyRepo myRepo;
@Before
public void init() throws Exception {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build();
}
该类中的测试如下所示:
@Test
@Transactional
@Rollback
public void test1() throws Exception {
MyClass user = myRepo.find(ID);
.....
mockMvc.perform(post(myRequest)
.contentType(CONTENT_TYPE)
.content(user))
.andExpect(status().is(MY_STATUS))
.andExpect(content().contentType(CONTENT_TYPE))
.andExpect(content().json(MY_RESPONSE.toString(), false));
}
我已将此 jar 作为依赖项添加到 maven 项目中。
是否可以以某种方式配置和更改 MyTests 类或 jar 中的某些内容,以便我可以在 maven 项目的测试部分中运行这些测试(MyTests),我在其中添加了这个 jar 作为依赖项。我想调用这些测试,例如,像这样:
@Autowired
MyTests myTests;
.....
myTests.runAllTests();
谁能告诉我怎么做这样的事情?
我希望 jar 中的这些测试能够运行并测试我的 Maven 项目及其数据库。
解决方案
您可以使用:
public static void main(String[] args) throws Exception {
JUnitCore.main(
"TestCase1");
}
或者
仔细检查 url 以查看 case.jar 是否是您声明的位置。还要检查TestCase1
类是否在任何包中。例如,如果TestCase1
在 comp.lang.java 包中并且在 case.jar 根目录的 comp/lang/java/ 文件夹下,那么您需要编写:
loader.loadClass("comp.lang.java.TestCase1");
例子:
import java.net.URL;
import java.net.URLClassLoader;
import junit.framework.TestResult;
import junit.textui.TestRunner;
public class MyTestRunner {
public static void main(String[] args) throws Exception{
URL url = new URL("file:///d:/case.jar");
URLClassLoader loader = new URLClassLoader(new URL[]{url});
loader.loadClass("TestCase1");
TestRunner runner = new TestRunner();
TestResult result = runner.start(new String[]{"TestCase1"});
System.out.println(result.toString());
}
}
推荐阅读
- javascript - 有没有办法在 js 中进行 eval() 导出
- python - 散点图图例 - 标记每个形状代表的内容
- rest - 您保护 Express.js REST API 的方法是什么?
- c - 使用指向新元素的指针而不是 int 在列表的开头插入一个元素
- c# - 有没有办法从其类型中获取类引用?
- matlab - 选择并更改矩阵中未由索引返回的元素的值
- c# - c# 中的 PowerShell Scriptblck
- laravel - 在 laravel 项目中,我试图从 mysql 数据库表“类别”中获取数据,除了一个“标题”之外的所有字段都返回
- javascript - 与 Vuex、axios 和多个组件实例进行封装数据共享
- ruby-on-rails - 未初始化的常量 GraphqlController::GraphQLSchema