如果您使用@ComponentScan和Jpa存储库,我发现编写@SpringBootTest非常困难。有人可以建议吗?这应该是非常重要的东西,但它没有在任何地方记录。
@SpringBootApplication
@ComponentScan(
excludeFilters = {
@ComponentScan.Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@ComponentScan.Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) },
basePackageClasses = {Main.class, Other.class})
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
}
并且已发现的配置类之一具有:
@Configuration
@EnableJpaRepositories("jpa")
现在我想创建测试,它将理想地只是JPA存储库的一个子集,而不是其他任何东西,除非我这样说。即,没有来自生产源代码的配置。这似乎几乎无法表达。这是我能得到的地方:
@RunWith(SpringRunner.class)
@SpringBootTest
@Import(TestIT.TestConfig.class)
public class TestIT {
@Configuration
@EnableJpaRepositories("jpa")
@AutoConfigureDataJpa
@AutoConfigurationPackage
public static class TestConfig {
//here will be beans for test.
}
所以这个配置会产生错误
java.lang.IllegalArgumentException: Not a managed type ...my jpa repository class
这可能意味着,jpa
包不属于自动配置包。如果可能的话,不知道如何添加它。
好的,另一种方法。一些消息来源推荐:
@RunWith(SpringRunner.class)
@SpringBootTest
@Import(TestIT.TestConfig.class)
public class TestIT {
EnableJpaRepositories("jpa")
@EntityScan(basePackages = "jpa.entities")
//@TestPropertySource("classpath:application.properties")
@EnableTransactionManagement
public static class TestConfig {
//here will be beans for test.
}
但是这个与caused by: java.lang.IllegalArgumentException: At least one JPA metamodel must be present!
失败了
任何提示?
首先,没有特别需要在主应用程序启动文件中添加@ComponentScan。 @SpringBootApplication
就足够了。
现在关于测试案例:我使用powermockito我的所有测试用例通常如下所示: -
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)
@PrepareForTest({ ContextProvider.class, ConfigurationUtils.class, Utils.class })
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class TestIT {
在条款中@PrepareForTest
提到了你用注释@Mock提到的所有类。例如无需提及任何repo(我们编写查询的DAO层接口)接口。所以你的回购声明就像:
private SoftwareRepo softwareRepo;
你会在执行时使用它
softwareInventoryRepo = PowerMockito.mock(SoftwareRepo.class);
好的,经过大量的搜索(徒劳),甚至更多的尝试,我想我已经回答了。
回顾一下:
你有主要课程(感谢@Bhushan Shinde):
@SpringBootApplication(scanBasePackageClasses = {Main.class, Other.class})
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
}
和一些配置:
@Configuration
@EnableJpaRepositories("jpa")
public class Config
因此,要使用SpringBootTest并从头开始配置所有测试,忽略生产配置,您可以:
@RunWith(SpringRunner.class)
@SpringBootTest(
webEnvironment = SpringBootTest.WebEnvironment.NONE,
classes = TestIT.TestConfig.class)
//@Import(TestIT.TestConfig.class)
public class TestIT {
@Configuration
@AutoConfigureDataJpa
@EnableJpaRepositories("jpa") //fake package names, obviously
@EntityScan(basePackages = "jpa.entities")
// @TestPropertySource("classpath:application.properties")
@EnableTransactionManagement
public static class TestConfig {
//test related beans & config.
}
//tests here.
}
也许这里有额外的东西,但是在谷歌搜索和尝试之后这对我来说已经足够了。