我对RestController进行了简单的测试。我希望$[1].parent_id
返回Long作为对象而不是整数原语。如果parent_id
处于长数字范围且>整数范围(例如:2147483650L)。
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
@WebAppConfiguration
public class TransactionServiceControllerTest {
@Before
public void setup() throws Exception {
this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
// I copy this from my RestController class
this.transactions = Arrays.asList(
new Transaction(100d, "car", null),
new Transaction(100d, "table", 12L)
);
}
@Test
public void readSingleBookmark() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/transaction/"))
.andExpect(content().contentType(contentType)) // ok
.andExpect(jsonPath("$", hasSize(2))) // ok
//omitted
andExpect(jsonPath("$[1].parent_id",is(this.transactions.get(1).getParentId())));
} //assertion fail
Expected: is <12L>
but: was <12>
另一项测试的结果:
Expected: is <12L>
but: was <2147483650L> //return Long instead int
这是我的JacksonConfiguration
@Configuration
public class JacksonConfiguration {
@Bean
@Primary
public ObjectMapper objectMapper() {
final ObjectMapper objectMapper = new ObjectMapper();
//supposed to be this is the magic trick but it seems not..
objectMapper.enable(DeserializationFeature.USE_LONG_FOR_INTS);
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_ABSENT);
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
return objectMapper;
}
}
我的POJO
public class Transaction {
private double ammount;
private String type;
private Long parentId;
public Transaction(Double ammount, String type, Long parentId) {
//omitted
}
//setter and getter omitted
}
MyRestController
@RestController
@RequestMapping("transaction")
public class TransactionServiceController {
@RequestMapping(method = RequestMethod.GET)
List<Transaction> getTransaction() {
return
Arrays.asList(
new Transaction(100d, "car", null),
new Transaction(100d, "table", 12L)
);
}
}
和Application.java
@SpringBootApplication
public class Application {
public static void main(String[] args){
SpringApplication.run(Application.class,args);
}
}
答案 0 :(得分:8)
MockRestServiceServer
一起使用。
MockMvc
一起使用。
一个选项(我尚未亲自验证)将尝试不同的JsonProvider
。这可以通过com.jayway.jsonpath.Configuration.setDefaults(Defaults)
设置。
如果您确定Long
始终可以安全缩小到int
,则可以使用以下内容:
andExpect(jsonPath("$[1].parent_id",is(this.transactions.get(1).getParentId().intValue())));
唯一的另一个选择是编写自定义Matcher
,在执行实际匹配之前将传入的Integer
转换为Long
。
答案 1 :(得分:3)
从Spring 5.2开始,您可以将type作为jsonPath()
方法的第三个参数提供:
public static <T> ResultMatcher jsonPath(String expression, Matcher<T> matcher, Class<T> targetType)
在这种情况下,它将是:
andExpect(jsonPath("$[1].parent_id",is(this.transactions.get(1).getParentId()), Long.class));