首页 > 解决方案 > 如何从 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 项目及其数据库。

标签: javamavenspring-boottestingjar

解决方案


您可以使用:

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());
}
}

推荐阅读