Spring Boot测试API和存储库的多个类

时间:2019-02-11 16:27:48

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

我为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和存储库类中的所有测试的最佳方法是什么?

1 个答案:

答案 0 :(得分: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脚趾执行一系列测试或程序包创建测试配置文件。