如何测试spring数据jpa项目

pnwntuvh  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(472)

我有一个spring应用程序,有这些依赖项。该项目只包含另一个应用程序的服务和存储库,因此没有主类

<dependencies>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>2.2.1.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.1.RELEASE</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

我想测试一个服务,所以这是我的服务类:
我有这个配置文件:

@EnableJpaRepositories(basePackages = "com.bonanza.backend.repository")
@EntityScan(basePackages = "com.bonanza.backend.service")
@EnableTransactionManagement
@EnableCaching
@Profile("dev")
@Configuration
@PropertySource("file:///${user.home}/.bonanza/backend-dev.properties")
public class DevBackendConfig {
}

测试包上的这个:

@Configuration
@Import({DevBackendConfig.class})
public class TestBackendConfig {
}

这是我的测试课:

@ContextConfiguration(classes={TestBackendConfig.class})
@RunWith(SpringRunner.class)
public class CompanyServiceTests {

    @Autowired
    protected CompanyService companyService;

..
}

但是当我运行测试时,我有一个错误:

java.lang.IllegalStateException: Failed to load ApplicationContext

    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:132)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:123)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:244)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': Cannot create inner bean '(inner bean)#636e8cc' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#636e8cc': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
bqf10yzr

bqf10yzr1#

spring似乎不能为用户jpa repo创建bean。没关系,因为如果你在做单元测试,你应该只测试你的应用程序的一层,并模拟依赖关系。这可以在mockito框架的帮助下完成。这是一篇很好的介绍博客文章。生成的测试代码如下所示(我们模拟了所有依赖项,并在需要时创建了存根):

@RunWith(MockitoJUnitRunner.class)
public class TestUserResolver {
@Mock
private UserRepository userRepository;
@Mock
private RightsRequestRepository rightsRequestRepository;
@Mock
private NotifierService notifierService;

private UserResolver userResolver;

@Test
public void testListAllUsers() {
    when(userRepository.findAll()).thenReturn(getFakeUserList());
    userResolver = new UserResolver(userRepository, rightsRequestRepository, notifierService);

    List<UserDTO> cs = userResolver.getAllUsers();
    assertEquals(1, cs.size());
}
....}

相关问题