以下のようなSpring BootプロジェクトをJunitでテストコードを書いていますが
どうしてもパラメーターが渡されて来ないので困っています。
(※lombokも使っています。)
以下を実行すると ItemInfo
は値が渡って来ますが、ItemDetail
は渡って来ません。
Controllerを修正せず、渡す方法はないのでしょうか?
そもそも2つのオブジェクトでパラメータで渡そうとしている事が問題でしょうか?
- 構造体
@Data
public class ItemDetail {
private Long deid;
private String type;
}
@Data
public class ItemInfo {
private Long id;
private String name;
}
- Controller
@PostMapping("/item/create")
public String create(ItemInfo itemInfoParam,
Optional<ItemDetail> itemDetailParam,
HttpHeaders headers) {
val itemDetail = itemDetailParam.orElseThrow(() -> new BadRequestException());
service.create(itemInfoParam, itemDetail);
return "OK";
}
- 以下はテストコードの一部
@Autowired
WebTestClient webTestClient;
@MockBean
SampleService mockservice;
@Test
public void webTestClient(){
when(mockservice.create()).thenReturn("OK");
webTestClient.post()
.uri(uriBuilder - > uriBuilder
.path("/item/create")
.queryParam("id", 1L)
.queryParam("name", "name1") // ここまでがItemInfo
.queryParam("deid",2L)
.queryParam("type", "box") // ここまでがItemDetail
.build()
)
.exchange()
.expectStatus().isOk()
.expectBody(String.class).isEqualTo("OK");
}
itemInfoParam
にもitemDetailParam
にも想定通りのオブジェクトが割り当てられています。質問文に書かれている情報以外のところに原因があると思われます。