当前位置: 首页 > 知识库问答 >
问题:

在JUnit中用(out)存储库对Spring Boot服务类进行单元测试

胡俊弼
2023-03-14

我正在开发一个基于spring boot的webservice,其结构如下:

控制器(REST)-->服务-->存储库(如某些教程中所建议的)。

@Component
public class SessionService {
    @Autowired
    private SessionRepository sessionRepository;
    public void MethodIWantToTest(int i){
    };
    [...]
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
public class SessionServiceTest {

    @Configuration
    static class ContextConfiguration {
        @Bean
        public SessionService sessionService() {
            return new SessionService();
        }
    }

    @Autowired
    SessionService sessionService;
    @Test
    public void testMethod(){
    [...]
  }
}
@Configuration
@EnableJpaRepositories(basePackages={"com.myApp.repositories"})
@EnableTransactionManagement
public class JpaConfig {


    @Bean
    public ComboPooledDataSource dataSource() throws PropertyVetoException, IOException {
        ...
    }

   @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) {
        ...
    }


    @Bean
    public JpaVendorAdapter jpaVendorAdapter() {
        ...
    }

    @Bean
    public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
   ...
    }

    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
  ... 
   }
}

共有1个答案

越新霁
2023-03-14

使用@SpringBootTest和@RunWith(SpringRunner.class)加载上下文

@RunWith(SpringRunner.class)
@SpringBootTest
class Demo{
    @Test
    void contextLoad(){}
}
 类似资料:
  • 首先,我是Spring Hibernate开发的新手。遵循了很多教程书籍,我创建了一个主要基于Spring、Hibernate标准的示例应用程序,我已经开始为Repository(DAO)方法编写一些测试用例,即查找、查找、保存、删除。 当我执行测试类时,这真是太疯狂了,并不是所有的测试用例都能正确地为ex执行。尤其是find 当我完全执行以上所有测试用例时 甚至更新测试用例的行为也很奇怪,因为在

  • 我有DaoImpl类: 我的测试是: 测试是成功的,但是当我运行具有覆盖率的junit测试时,它显示方法没有被覆盖,因此我的整体单元测试行覆盖率低于要求。我们能涵盖那部分吗?如果是,我们怎么做?谢了。

  • 我在go中对gRPC服务进行单元测试时遇到困难。 我看了一下测试gRPC服务,但它对我不起作用,不确定我做错了什么。 Add方法的gRPC服务实现: Add方法的单元测试: 项目目录结构 抛出一个错误,称为。 我对非常陌生,找不到解决方法。

  • 我有一个Spring Data JPA存储库,只要不添加Spring Security性依赖项(spring-boot-starter-security)并在存储库上添加相应的方法授权注释,单元测试就可以正常工作。添加后,在运行单元测试时,我会得到一个AuthenticationCredentialsNotFound异常。 如何在单元测试中“验证”对存储库方法的调用?

  • 我想测试我的SpringBoot应用程序,它使用cassandra作为CrudRepository。我最终得到了 具有 和 这就导致了 如果我使用旧版本的cassandra-unit-Spring 它以NullPointerException结束,因为没有注入值repo。 来源https://github.com/StephanPraetsch/spring.boot.cassandra.unit

  • 我是TDD的忠实粉丝,我通常在编写代码之前为我的大学作业编写测试用例。下面是我作业的界面: