Java Spring 单元测试 JPA 存储库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24368090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 11:49:18  来源:igfitidea点击:

Spring Unit test JPA repository

javaspringunit-testingspring-mvcjpa

提问by Egizeris

I'm new to Spring framework. I need to write Unit Test for JPA repository. I'm trying simple repository saveAndFlush()method. But nothing saves in my repository. Here is my source code:

我是 Spring 框架的新手。我需要为 JPA 存储库编写单元测试。我正在尝试简单的存储库saveAndFlush()方法。但是我的存储库中没有保存任何内容。这是我的源代码:

TestContext.class

测试上下文.class

@Configuration 
@PropertySource("classpath:log4j.properties") 
public class TestContext {

    @Bean
    public RoleService roleService() {
        return Mockito.mock(RoleService.class);
    }

    @Bean
    public RightService RightService() {
        return Mockito.mock(RightService.class);
    }

    @Bean
    public RoleRepository RoleRepository() {
        return Mockito.mock(RoleRepository.class); 
    }
}

RoleServiceTest.class

RoleServiceTest.class

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {TestContext.class})
@WebAppConfiguration
public class RoleServiceTest {

    @Autowired
    private RoleRepository roleRepository;

    @Test
    public void TestServices() throws Exception {
        RoleDetails first = new RoleDetails();
        first.setId("1");
        first.setDescription("First Description");
        first.setName("First");
        roleRepository.saveAndFlush(new RoleEntity(first));
        roleRepository.save(new RoleEntity(first));
        List<RoleEntity> roles = new ArrayList<RoleEntity>();
        roles = roleRepository.findAll();
        System.out.println(roles);
        assertEquals(1, roles.size());
    }
}

And error:

和错误:

java.lang.AssertionError: expected:<1> but was:<0>

I'm almost sure that problem occurs because of testContext.Class. I used this class to test my controller and it worked well, but now i need to test my database and i don't know how to modify contextConfiguration. I hope somone will help me. Thanks in advance!

我几乎可以肯定这个问题是由于 testContext.Class 发生的。我用这个类来测试我的控制器,它运行良好,但现在我需要测试我的数据库,我不知道如何修改 contextConfiguration。我希望有人会帮助我。提前致谢!

采纳答案by radusezciuc

The problem is from the TestContext indeed. You try to save your object using a mock object, which is not correct.

问题确实来自 TestContext 。您尝试使用模拟对象保存对象,这是不正确的。

The solution is to use the real repository. For this, you need to follow the next steps:

解决方案是使用真正的存储库。为此,您需要执行以下步骤:

  1. Annotate your RoleRepository with the @Repositoryannotation and extend the class with JpaRepository(RoleEntity,ID)(where ID is the type you declared the id of the RoleEntity).
  2. Add the RoleRepository to your Context Configuration class (the real one, not a test one). You can do this by adding @EnableJpaRepositories(value="your.repository.package").
  3. Replace the TestContext.class from your @ContextConfigurationannotation on your RoleServiceTest class with your real Context Configuration class you used to configure your Spring based project.
  1. 与注释您RoleRepository @Repository注解,并与扩展类JpaRepository(RoleEntity,ID) (其中ID是你声明的RoleEntity的ID类型)。
  2. 将 RoleRepository 添加到您的 Context Configuration 类(真正的类,而不是测试类)。您可以通过添加@EnableJpaRepositories(value="your.repository.package")来做到这一点。
  3. 将RoleServiceTest 类上@ContextConfiguration注释中的 TestContext.class 替换为用于配置基于 Spring 的项目的真实 Context Configuration 类。

I hope my answer helps, if you still need help feel free to ask again!

希望我的回答对您有所帮助,如果您还需要帮助,请随时再次提问!

回答by JB Nizet

Your repository is a mock object. A mock object, by definition, is an object that doesn't do what it should normally do, but does what you tell it to do in the test.

您的存储库是一个模拟对象。模拟对象,根据定义,是一个不做它通常应该做的事情,但做你在测试中告诉它做的事情的对象。

To test the repository, the repository must be a real one. Your context class should thus rather have

要测试存储库,存储库必须是真实的。因此,您的上下文类应该具有

@Bean
public RoleRepository RoleRepository() {
    return new RoleRepositoryImpl(); // or whatever the class implementing the repository is 
}

回答by Baker

If using Spring Boot, creating a web app and you're running off of a main() method within an Application.class you could use:

如果使用 Spring Boot,创建​​一个 Web 应用程序并且您正在运行 Application.class 中的 main() 方法,您可以使用:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
public class MyUnitTest {

    Some someInstance = new Some();

    @Autowired
    private SomeRepository someRepository;
}

@Test
public void testSomeClass() throws Exception {
    Some savedSome = someRepository.save(someInstance);
    assertEquals(1, someRepository.count());
}