4
我對RestController有一個簡單的測試,我期望$[1].parent_id
返回Long作爲一個對象而不是整數原語。這將返回長,如果parent_id
是在相當長的編號範圍和>整數範圍(如:2147483650L)。從另一個測試如何強制`.andExpect(jsonPath()`返回Long/long代替int爲int數爲jackson分析器
@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);
}
}
只是一個友好的筆記,如果你發現你的問題的答案可以接受的話,請隨時[接受](http://stackoverflow.com/help/accepted-answer),如果你想。 –
今天(1年後)我真的很抱歉,我只是意識到我點擊了錯誤的按鈕。我認爲接受答案是'''向上按鈕''。但它是一個'''檢查按鈕'','''Stackoverflow新用戶歡迎如何''''進行了徹底的解釋。許多人感謝SamBrenner友好(幾乎被忽視)的提醒。 – slawalata
不用擔心。乾杯! ;-) –