标签: spring-boot-test

使用自定义基础存储库配置 Spring @DataJpaTest

让我们假设一个自定义的基本JpaRepository实现如下所示。

public class SimpleCustomJpaRepository<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> implements CustomJpaRepository<T, ID> {

    @Override
    public List<T> findAllCustom() {

        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

基础存储库是使用@EnableJpaRepositories注释注册的。

@EnableJpaRepositories(value = "org.somebody.repository", repositoryBaseClass = SimpleCustomJpaRepository.class)
Run Code Online (Sandbox Code Playgroud)

UserRepository我应该如何为扩展接口配置集成测试CustomJpaRepository,并因此应该使用自定义基本实现?

public interface UserRepository extends CustomJpaRepository<User, Long> { ... }
Run Code Online (Sandbox Code Playgroud)

当前使用的集成测试失败并显示org.springframework.data.mapping.PropertyReferenceException: No property findAllCustom found for type User!。实际上,它无法加载,ApplicationContext因为我的自定义基础存储库实现在集成测试期间未注册,因此未findAllCustom找到 的实现。

@ExtendWith(SpringExtension.class)
@DataJpaTest
class UserRepositoryTest {

    @Autowired
    private UserRepository userRepository. 
}
Run Code Online (Sandbox Code Playgroud)

JpaRepository我应该如何结合 JPA 存储库集成测试来注册自定义实现?

java spring spring-data-jpa spring-boot spring-boot-test

3
推荐指数
1
解决办法
1597
查看次数

SpringBoot单元测试-Service方法未调用

我是单元测试的新手。参考谷歌后,我创建了一个测试类来测试我的控制器,如下所示:

@RunWith(SpringRunner.class)
@WebMvcTest(PromoController.class)
public class PromoApplicationTests {
    @Autowired
    protected MockMvc mvc;
    @MockBean PromoService promoService;
   
   
   protected String mapToJson(Object obj) throws Exception {
      ObjectMapper objectMapper = new ObjectMapper();
      return objectMapper.writeValueAsString(obj);
   }
   protected <T> T mapFromJson(String json, Class<T> clazz)
      throws JsonParseException, JsonMappingException, IOException {
      
      ObjectMapper objectMapper = new ObjectMapper();
      return objectMapper.readValue(json, clazz);
   }
   
   @Test
    public void applyPromotionTest_1() throws Exception {
           String uri = "/classPath/methodPath";
           List<Cart> cartLs = new ArrayList<Cart>();
          // added few objects to the list
           
           String inputJson = mapToJson(cartLs);
           MvcResult mvcResult = …
Run Code Online (Sandbox Code Playgroud)

java spring-boot spring-boot-test

3
推荐指数
1
解决办法
921
查看次数

Lombok 生成的构造函数无法在 SpringBootTest 中隐式自动装配

我想通过构造函数将A类注入到B类中。

测试目录中的类结构

@Component
public class A {
}
Run Code Online (Sandbox Code Playgroud)
import lombok.RequiredArgsConstructor;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
@RequiredArgsConstructor
public class B {
    private final A a;

    @Test
    public void testB() {
        System.out.println("testB");
    }
}
Run Code Online (Sandbox Code Playgroud)

但是当我运行测试时抛出以下错误。

org.junit.jupiter.api.extension.ParameterResolutionException: No ParameterResolver registered for parameter [final com.wen.h2.A a] in constructor [public com.wen.h2.B(com.wen.h2.A)].
    at org.junit.jupiter.engine.execution.ExecutableInvoker.resolveParameter(ExecutableInvoker.java:200)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.resolveParameters(ExecutableInvoker.java:183)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:74)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeTestClassConstructor(ClassBasedTestDescriptor.java:342)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.instantiateTestClass(ClassBasedTestDescriptor.java:289)
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.instantiateTestClass(ClassTestDescriptor.java:79)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.instantiateAndPostProcessTestInstance(ClassBasedTestDescriptor.java:267)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$2(ClassBasedTestDescriptor.java:259)
    at java.util.Optional.orElseGet(Optional.java:267)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$3(ClassBasedTestDescriptor.java:258)
    at org.junit.jupiter.engine.execution.TestInstancesProvider.getTestInstances(TestInstancesProvider.java:31)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$prepare$0(TestMethodTestDescriptor.java:101)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:100)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:65)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$prepare$1(NodeTestTask.java:111)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at …
Run Code Online (Sandbox Code Playgroud)

java lombok spring-boot-test

3
推荐指数
1
解决办法
1326
查看次数

运行Spring Boot测试时访问配置类中的@LocalServerPort

我正在使用我的SpringBootTest. 我可以使用注释检索测试类中的随机端口@LocalServerPort

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ContextConfiguration(classes = {MyTest.LocalConfig.class})
public class MyTest {

  @LocalServerPort
  private Integer port;
Run Code Online (Sandbox Code Playgroud)

不幸的是,我无法检索类中的随机端口Configuration,我想在类中使用随机端口创建测试 bean:

  @TestConfiguration
  public static class LocalConfig {

    @Bean
    public MyBean myBean(@Value("${local.server.port}") int port) {
Run Code Online (Sandbox Code Playgroud)

这里我得到这个错误:

Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 
'local.server.port' in value "${local.server.port}"
Run Code Online (Sandbox Code Playgroud)

spring-boot spring-boot-test

3
推荐指数
1
解决办法
2173
查看次数

@WebMvcTest需要@Import(SecurityConfig.class)来启用SpringSecurity

首先,重要的是要指定应用程序已经部署并且我们的 spring 安全配置有效。如果未经身份验证的用户尝试访问 API 的任何端点,则会返回 401 Unauthorized。

@WebMvcTest接下来,在这个示例示例中,我想使用和 来测试控制器spring security

@WebMvcTest(EmployeeController.class)   
@Import(SecurityConfig.class)
class EmployeeControllerTest {

    @Autowired
    private WebApplicationContext ctx;

    protected MockMvc mvc;

    @MockBean
    private EmployeeService service;

    @BeforeEach
    public void setUp() {
        this.mvc = MockMvcBuilders
                .webAppContextSetup(ctx)
                .apply(springSecurity())
                .build();
    }

    @Test
    void unauthorized_role_should_return_401() {

       mvc.perform(get("/employees/1").accept(MediaType.APPLICATION_JSON)
            .with(SecurityMockMvcRequestPostProcessors.user("manager").roles("UNKNOWN")))
            .andExpect(status().isUnauthorized())
    }
}
Run Code Online (Sandbox Code Playgroud)

这段代码有效,但我不明白为什么需要将该SecurityConfig类导入到测试类中。事实上,如果我删除@Import,mockMvc返回 200。但是,我发现的每个示例项目都Github只是使用@WebMvcTest,即使该项目有一个SecurityConfig

spring-security spring-boot mockmvc spring-boot-test

3
推荐指数
1
解决办法
977
查看次数

Spring集成测试-覆盖bean的惯用方式

如何在Spring(Boot)Integration Tests中以惯用方式覆盖bean?

到目前为止,我的源代码配置如下:

@Configuration
class ApplicationConfiguration {
  @Bean
  CarsRepository carsRepository() {
    // return some real sql db
  }
}
Run Code Online (Sandbox Code Playgroud)

并进行如下测试:

@SpringBootTest
class ApplicationISpec extends Specification {
  @Configuration
  @Import(Application.class)
  static class TestConfig {
    @Bean
    @Primary
    CarsRepository testsCarsRepository() {
      // return some in-memory repository
    }
  }

  def "it can do stuff with cars"() {
    // do some REST requests to application and verify it works
    // there is no need to make real calls to real DB
  }
}
Run Code Online (Sandbox Code Playgroud)

首先,测试bean testsCarsRepository方法必须与原始方法不同(这并不明显,也没有警告/错误)。但是最后一个问题是:在集成测试中用Spring覆盖bean的惯用方式是什么? …

spring spring-boot spring-boot-test

2
推荐指数
1
解决办法
1732
查看次数

模拟投影结果Spring Data JPA

我在我的spring boot项目中使用spring data jpa。

我正在触发JPQL查询,并使用投影来存储查询结果。我的投影:

public interface VeryBasicProjection {
    String getTitle();
    String getUrl();
}
Run Code Online (Sandbox Code Playgroud)

我的服务称为此投影:

public List<VeryBasicDTO> getLatestData(int limit){

        // Pageable for Limit
        Pageable pageable = new PageRequest(0, limit);

        // Get Data from DB
        List<VeryBasicProjection> latestData = tableRepository.getLatestData("live", 2,pageable);
        List<VeryBasicDTO> responseDTO = new ArrayList<>();

        // Map Projection to DTO
        for(VeryBasicProjection veryBasicProjection : latestData){
            VeryBasicDTO veryBasicDTO = new VeryBasicDTO();
            veryBasicDTO.buildDTO(veryBasicProjection);
            responseDTO.add(veryBasicDTO);
        }

        return responseDTO;
    }
Run Code Online (Sandbox Code Playgroud)

现在,我想使用Mockito(单元测试用例)测试此服务,我正在使用when和thenReturn模拟对存储库的调用。

我的问题是如何模拟存储库的结果?那么返回应该是什么?我的意思是如何创建投影实例和setData?

mockito spring-boot-test

2
推荐指数
4
解决办法
2121
查看次数

Spring Boot-Web MVC测试未找到控制器映射

此spring-boot项目中,以下操作WebMvcTest失败,因为未找到的GET /items映射ItemController

@RunWith(SpringRunner.class)
@WebMvcTest(ItemController.class)
@AutoConfigureMockMvc
public class Test_ItemController {

    @Autowired
    private MockMvc mvc;

    @MockBean
    private ItemDao dao;

    @MockBean
    private CartDao cartDao;

    @Test
    public void test() throws Exception {
        // setting up mock response
        Cart cart = new Cart();
        cart.setId(1);

        Item item = new Item();
        item.setCart(cart);
        item.setItemName("toothbrush");
        item.setId(1);
        //---------------------

        List<Item> items = new ArrayList<>();
        items.add(item);

        given(this.dao.findAll()).willReturn(items);
        this.mvc.perform(get("items").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk());
    }
}
Run Code Online (Sandbox Code Playgroud)

错误是:

2018-02-26 12:10:45.816  WARN 12252 --- [           main] o.s.web.servlet.PageNotFound             : 
   No mapping found for HTTP …
Run Code Online (Sandbox Code Playgroud)

spring spring-mvc spring-mvc-test spring-boot spring-boot-test

2
推荐指数
1
解决办法
2250
查看次数

SpringBootTest:没有可用的'org.springframework.test.web.servlet.MockMvc'类型的合格bean:

嘿,在创建测试用例时,我已经开始使用spring boot Test框架进行spring-boot junit测试,我面临以下问题。

    import static org.hamcrest.Matchers.containsString;
    import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
    import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringRunner;
    import org.springframework.test.web.servlet.MockMvc;


    @RunWith(SpringRunner.class)
    @SpringBootTest
    @AutoConfigureMockMvc
    public class ApplicationTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void shouldReturnDefaultMessage() throws Exception {
        this.mockMvc.perform(get("/")).andDo(print()).andExpect(status().isOk())
                .andExpect(content().string(containsString("Hello World")));
    }
}
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,我遇到了错误

    Caused by: **org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No qualifying bean of type 'org.springframework.test.web.servlet.MockMvc' available: 
expected at least 1 bean which qualifies as autowire candidate.
 Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}** …
Run Code Online (Sandbox Code Playgroud)

junit4 spring-boot mockmvc spring-boot-test

2
推荐指数
3
解决办法
5689
查看次数

JUnit的@TestMethodOrder注释不起作用

我在进行以下集成测试时遇到问题

import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;

@SpringBootTest
@ActiveProfiles("test")
@TestMethodOrder(OrderAnnotation.classs)
public class FooServiceIT {
    @Test
    @Order(1)
    void testUploadSuccess() { ... }
    @Test
    @Order(2)
    void testDownloadSuccess() { ... }
    @Test
    @Order(3)
    void testDeleteSuccess() { ... }
}
Run Code Online (Sandbox Code Playgroud)

我希望在运行测试时执行顺序为1、2、3,但是由于某种原因,实际的执行顺序为2、3、1。

Tbh,我不知道为什么注释不起作用。我正在将Spring Boot 2.1.3与JUnit 5.4一起使用。

java spring-boot junit5 spring-boot-test

2
推荐指数
4
解决办法
3468
查看次数