标签: spring-test-mvc

如何直接从Spring Test MvcResult json响应中检索数据?

我想从json响应中撤消一个值,以便在我的其余测试用例中使用,这是我现在正在做的事情:

MvcResult mvcResult = super.mockMvc.perform(get("url").accept(MediaType.APPLICATION_JSON).headers(basicAuthHeaders()))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$[0].id", is(6))).andReturn();

String responseAsString = mvcResult.getResponse().getContentAsString();
ObjectMapper objectMapper = new ObjectMapper(); // com.fasterxml.jackson.databind.ObjectMapper
MyResponse myResponse = objectMapper.readValue(responseAsString, MyResponse.class);

if(myResponse.getName().equals("name")) {
    //
    //
}
Run Code Online (Sandbox Code Playgroud)

我想知道是否有一种更优雅的方法可以直接从中检索值,MvcResult例如jsonPath进行匹配?

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

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

DeferredResult 的 Spring MVC 单元测试不调用超时回调

我在 Java 7 上使用 Spring 4.3.18 和 Spring Boot 1.5.14。

我正在实现一个 RestController 端点,它返回DeferredResult带有超时回调的 a 。我正在尝试为超时回调编写单元测试,但无法获得MockMvc调用超时回调的单元测试。

为了测试的目的,我写了这个端点:

@PostMapping("/test")
public DeferredResult<String>
testit() {
    logger.info("testit called");
    final DeferredResult<String> rv = new DeferredResult<>(1000L);
    rv.onTimeout(new Runnable() {
        @Override
        public void run() {
            logger.info("run called");
            rv.setResult("timed out");
        }
    });
    return rv;
}
Run Code Online (Sandbox Code Playgroud)

和这个单元测试:

@Autowired
private MockMvc mockMvc;

@Test
public void testTest() throws Exception {
    MvcResult result = mockMvc.perform(post("/rest/tasks/test"))
        .andExpect(request().asyncStarted())
        .andReturn();
    result.getAsyncResult(1500);
    mockMvc.perform(asyncDispatch(result))
        .andExpect(status().isOk())
        ;
}
Run Code Online (Sandbox Code Playgroud)

(调用result.getAsyncResult(1500)基于https://jira.spring.io/browse/SPR-16869

当我运行此命令时,testit() …

java spring-mvc spring-test-mvc

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

是否可以在WebMvcTest中激活弹簧配置文件

给定一个类似的测试类:

@WebMvcTest
@RunWith(SpringRunner.class)
@SpringBootTest(properties = "spring.profiles.active=test")
public class MyControllerTest  {
... some tests
}
Run Code Online (Sandbox Code Playgroud)

我得到错误:

java.lang.IllegalStateException:配置错误:为测试类[com.example.MyControllerTest]找到了@BootstrapWith的多个声明:[@ org.springframework.test.context.BootstrapWith(value = class org.springframework.boot.test.autoconfigure .web.servlet.WebMvcTestContextBootstrapper),@ org.springframework.test.context.BootstrapWith(value = class org.springframework.boot.test.context.SpringBootTestContextBootstrapper)]

理想的目标是我只是在运行控制器测试,因此出于测试性能的原因,不想设置整个上下文-我只需要“ Web层”。

我可以删除该@SpringBootTest(properties = "spring.profiles.active=test")行-但是,现在我还没有激活测试配置文件,它可以通过属性以某种方式自定义Web上下文,例如将不再应用的杰克逊自定义。有没有一种方法可以只对“ Web层”进行测试并仍然激活弹簧轮廓?

我的环境是java version "10.0.2" 2018-07-17,spring boot1.5.16.RELEASE

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

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

MockBean 未注入 MVC 控制器测试中

我正在尝试与 Spring 应用程序上下文隔离来测试我的控制器。

这是我的控制器

@RestController
public class AddressesController {

    @Autowired
    service service;

    @GetMapping("/addresses/{id}")
    public Address getAddress( @PathVariable Integer id ) {
        return service.getAddressById(id);
    }
}
Run Code Online (Sandbox Code Playgroud)

我的服务界面

public interface service {
    Address getAddressById(Integer id);
}
Run Code Online (Sandbox Code Playgroud)

这是我的测试课

@ExtendWith(SpringExtension.class)
@WebMvcTest
public class AddressControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    service myService;

    @Test
    public void getAddressTest() throws Exception {
        Mockito.doReturn(new Address()).when(myService).getAddressById(1);
        mockMvc.perform(MockMvcRequestBuilders.get("/addresses/1"))
                .andExpect(status().isOk());
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我得到的异常:

org.mockito.exceptions.misusing.NullInsteadOfMockException:传递给when()的参数为空!正确存根的示例: doThrow(new RuntimeException()).when(mock).someMethod(); 另外,如果你使用 @Mock 注解,不要错过 initMocks()

就像服务从未被创建一样。我该如何解决这个问题?

@RunWith(SpringRunner.class)我们可以通过使用代替来解决这个问题@ExtendWith(SpringExtension.class)。有人可以解释为什么它有效吗?通常第一个注释适用于 junit4,第二个注释适用于 junit5。

java spring-mvc mockito spring-test-mvc

0
推荐指数
1
解决办法
4212
查看次数