【问题标题】:Spring boot Test multiple classes for API and repositorySpring boot 测试 API 和存储库的多个类
【发布时间】:2019-02-11 16:27:48
【问题描述】:

我为 Spring Boot 编写了测试,并且有 2 个类正在测试 API 和存储库。下面提供了骨架,

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@AutoConfigureMockMvc
public class AppointmentAPITest {


    /*
     * we need a system to simulate this behavior without starting a
     * full HTTP server. MockMvc is the Spring class that does that.
     * */
    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private AppointmentAPI api;


    // now the tests are going on

}

存储库测试类,

@ActiveProfiles("test")
@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class AppointmentRepositoryTest {


    @Autowired
    private TestEntityManager entityManager;

    @Autowired
    private AppointmentRepository repository;


    // write the test here 

}

如何使用一个类来运行它们?例如,如果类是AppointmentApplicationTests

@RunWith(SpringRunner.class)
@SpringBootTest
public class AppointmentApplicationTests {

    @Test
    public void contextLoads() {

    }

}

配置这个类以便调用 API 和 repo 类中的所有测试的最佳方法是什么?

【问题讨论】:

  • 你现在如何运行测试?你能举个例子吗?
  • 我从每个文件中单独运行它们。您还需要查看文件中的测试吗?
  • 不,我的意思是您只是执行“右键单击 -> 以 Junit 测试方式运行”之类的操作吗?
  • 任何构建工具 maven/gradle?
  • 你使用IDEA/Eclipse什么IDE?

标签: java spring unit-testing spring-boot integration-testing


【解决方案1】:

我认为最简单的方法是创建一个Suite 来运行一组测试,例如:

JUnit 4

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(Suite.class)
@Suite.SuiteClasses({
    some.package.AppointmentRepositoryTest,
    some.package.AppointmentApplicationTests
})
public class MySuite {
}

Junit5

@RunWith(JUnitPlatform.class)
@SelectClasses({some.package.AppointmentRepositoryTest,
    some.package.AppointmentAPITest.class})
public class JUnit5TestSuiteExample {
}

但是,这并不总是最好的方法。还考虑熟悉如何为 maven toe 创建测试配置文件执行一堆测试或包。

【讨论】:

  • 我需要这样的东西,但使用代码后出现错误-org.junit.platform.commons.util.PreconditionViolationException: Cannot create Launcher without at least one TestEngine; consider adding an engine implementation JAR to the classpath
  • @Arefe 只是猜测,但也许你正在尝试运行 junit5 而你应该使用 4?认为 spring-boot 有 4。5 与 4 有点不同,它需要在你的 POM 中有更多的 deps。
  • 我刚刚检查过,JUnit 4 的代码工作正常。不过,第二个注释必须是 @Suite.SuiteClasses({AppointmentRepositoryTest .class,AppointmentAPITest .class})
猜你喜欢
  • 2018-06-26
  • 1970-01-01
  • 2019-01-23
  • 2018-02-19
  • 2019-05-29
  • 1970-01-01
  • 2017-09-25
  • 2018-08-06
  • 1970-01-01
相关资源
最近更新 更多