【问题标题】:How to run tests from the custom jar inside maven project?如何从 Maven 项目中的自定义 jar 运行测试?
【发布时间】:2018-09-14 15:50:57
【问题描述】:

我创建了带有存储库 (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 项目及其数据库。

【问题讨论】:

    标签: java maven spring-boot testing jar


    【解决方案1】:

    你可以使用:

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

    【讨论】:

    • 有了这个,类MyTests中的WebApplicationContext,在jar里面,将是jar的WebApplicationContext而不是app,我在其中添加了这个依赖,对吧?
    猜你喜欢
    • 1970-01-01
    • 2014-05-22
    • 2014-04-10
    • 2021-10-09
    • 2017-11-18
    • 2020-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多