テスト時に予想されるステータスは200ですが、現在は代わりに404が表示されます。Mockidoエラーを使用したPOST要求のユニットテスト
私はMockidoをかなり新しくしています。もし私が紛失しているものがあれば、簡単です。私にお知らせください。
私のコントローラで、LongオブジェクトのListを取るPOSTリクエストを作成しました。例外が発生しない場合は、ステータスがOKを返します。
@PostMapping(path = "/postlist")
public ResponseEntity<Void> updateAllInList(@RequestBody List<Long> ids) {
try {
// method from ControllerService.java here using ids
return ResponseEntity.status(HttpStatus.OK).body(null);
} catch (InvalidContentException e) {
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body(null);
}
RESTクライアントを使用してPOSTすると、正しい結果が得られます。私はPOST生のペイロードは、このようなものです:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextHierarchy({ @ContextConfiguration(classes = RootConfiguration.class), @ContextConfiguration(classes = WebConfiguration.class) })
@Category(UnitTest.class)
public class ControllerTest {
private static final String POST_REQUEST = "[ 2, 1 ]";
@Autowired private WebApplicationContext webApplicationContext;
@Autowired private ControllerService controllerService;
private MockMvc mockMvc;
@Before
public void setUp() throws Exception {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build();
doNothing().when(this.controllerService).updateAllInList(anyList());
doThrow(InvalidContentException.class).when(this.controllerService).updateAllInList(null);
}
@Test
public void updateList() throws Exception {
this.mockMvc.perform(post("http://testhost/api/configuration/postlist").contentType(MediaType.APPLICATION_JSON_UTF8).content(POST_REQUEST))
.andExpect(status().isOk());
}
@Configuration
static class RootConfiguration {
@Bean
public ControllerService ControllerService() {
return Mockito.mock(ControllerService.class);
}
}
@Configuration
@EnableWebMvc
static class WebConfiguration extends WebMvcConfigurerAdapter {
@Autowired
private ControllerService controllerService;
@Bean
public Controller controller() {
return new Controller(controllerService);
}
}
}
マイ:
[
2, 1
]
はしかし、ユニットテストは、私がテストクラスを作成した方法は、このようなものです私は404
を与えています私のテストクラスでは、間違ったコンテンツを差し込んでいます。しかし、実際のPOSTのrawペイロードから使用したのと同じコンテンツをプラグインできないのはなぜですか?
ありがとうございました。
を試してみてください? –
@ KarlNicholasこんにちは、私の生のペイロードがこの形式で動作するときに、この形式でテストが失敗する原因となっているものがありますか?投稿時に生のペイロードにいくつかの余分な文字が自動的に追加されると思いますが、それは何ですか?ありがとう。 – pike
404が見つかりません: 'http:// testhost/api/configuration/postlist'は実際のURLですか? –