質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
JUnit

JUnitは、Javaで開発されたプログラムのユニットテストを行うためのアプリケーションフレームワークです。簡単にプログラムのユニットテストを自動化することができ、結果もわかりやすく表示されるため効率的に開発時間を短縮できます。

Java

Javaは、1995年にサン・マイクロシステムズが開発したプログラミング言語です。表記法はC言語に似ていますが、既存のプログラミング言語の短所を踏まえていちから設計されており、最初からオブジェクト指向性を備えてデザインされています。セキュリティ面が強力であることや、ネットワーク環境での利用に向いていることが特徴です。Javaで作られたソフトウェアは基本的にいかなるプラットフォームでも作動します。

Spring Boot

Spring Bootは、Javaのフレームワークの一つ。Springプロジェクトが提供する様々なフレームワークを統合した、アプリケーションを高速で開発するために設計されたフレームワークです。

Q&A

解決済

1回答

3915閲覧

mockmvcのparamメソッドで特定の値を受け取り、ControllerクラスのPOSTメソッドのテストを行いたい

soso0programmer

総合スコア35

JUnit

JUnitは、Javaで開発されたプログラムのユニットテストを行うためのアプリケーションフレームワークです。簡単にプログラムのユニットテストを自動化することができ、結果もわかりやすく表示されるため効率的に開発時間を短縮できます。

Java

Javaは、1995年にサン・マイクロシステムズが開発したプログラミング言語です。表記法はC言語に似ていますが、既存のプログラミング言語の短所を踏まえていちから設計されており、最初からオブジェクト指向性を備えてデザインされています。セキュリティ面が強力であることや、ネットワーク環境での利用に向いていることが特徴です。Javaで作られたソフトウェアは基本的にいかなるプラットフォームでも作動します。

Spring Boot

Spring Bootは、Javaのフレームワークの一つ。Springプロジェクトが提供する様々なフレームワークを統合した、アプリケーションを高速で開発するために設計されたフレームワークです。

0グッド

0クリップ

投稿2020/08/28 02:37

現在、mockmvcを使ってコントローラークラスのテスト(bulkRegistrationDeployTest)を行っています。
GETメソッドのテストプログラムは作成することができたのですが、POSTメソッドの作成で悩んでいます。

実現したいことは、paramsを使ってメソッドのパラメータ値を入れたいのですが、うまくいきません。
また、POSTメソッドのテストケースも具体的に何をすればいいのかわからない状況です。
もしよければ、現場などで行っているPOSTメソッドのテストケースなどを教えていただけたら幸いです。

参考にしたサイト:https://stackoverflow.com/questions/45044021/spring-mockmvc-request-parameter-list
https://qiita.com/ryo2132/items/ec10116238e1e1f333a1

Controllerクラス

1package com.example.demo.controller; 2 3import java.text.SimpleDateFormat; 4import java.util.ArrayList; 5import java.util.Date; 6import java.util.Optional; 7 8import javax.servlet.http.HttpSession; 9 10import org.springframework.beans.factory.annotation.Autowired; 11import org.springframework.stereotype.Controller; 12import org.springframework.web.bind.annotation.ModelAttribute; 13import org.springframework.web.bind.annotation.RequestMapping; 14import org.springframework.web.bind.annotation.RequestMethod; 15import org.springframework.web.servlet.ModelAndView; 16 17import com.example.demo.entity.DeploymentEntity; 18import com.example.demo.entity.UserEntity; 19import com.example.demo.form.UserForm; 20import com.example.demo.repository.DeploymentRepository; 21import com.example.demo.repository.UserRepository; 22import com.example.demo.service.UserService; 23 24@Controller 25public class DeployBulkController { 26 27 @Autowired 28 UserRepository rep; 29 30 @Autowired 31 DeploymentRepository rep2; 32 33 @Autowired 34 UserService us; 35 36 @Autowired 37 HttpSession ses; 38 39 40 @RequestMapping(value = "/bulk", method = RequestMethod.GET) 41 public ModelAndView view(ModelAndView mav) { 42 mav.setViewName("bulkRegistration"); 43 mav.addObject("title", "部署一括登録"); 44 ArrayList<UserEntity> empList = rep.findEmpByDeleteFlag(); 45 ArrayList<UserForm> empForm = us.userList(empList); 46 ArrayList<DeploymentEntity> depList = rep2.findDeploymentByDeleteFlag(); 47 48 49 mav.addObject("empData", empForm); 50 mav.addObject("depData", depList); 51 52 return mav; 53 } 54 55 @RequestMapping(value = "/depBulkRegister", method = RequestMethod.POST) 56 public ModelAndView bulkRegistrationDeploy(@ModelAttribute ArrayList<UserForm> uf, ModelAndView mav) { 57 58 59 for(UserForm u:uf) { 60 us.updateuser(u); 61 Optional<UserEntity> uel = rep.findById(u.getId()); 62 UserEntity ue = uel.get(); 63 64 Date date = new Date(); 65 SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); 66 // 日時情報を指定フォーマットの文字列で取得 67 String display = format.format(date); 68 ue.setEdit_date(display); 69 70 UserEntity loginEmp = (UserEntity) ses.getAttribute("loginEmp"); 71 ue.setEditer_id(loginEmp.getId()); 72 73 rep.saveAndFlush(ue); 74 } 75 76 return new ModelAndView("redirect:/depTop"); 77 } 78 79} 80
package com.example.demo; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import java.util.ArrayList; import javax.servlet.http.HttpSession; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import com.example.demo.controller.DeployBulkController; import com.example.demo.entity.DeploymentEntity; import com.example.demo.entity.UserEntity; import com.example.demo.form.UserForm; import com.example.demo.repository.DeploymentRepository; import com.example.demo.repository.UserRepository; import com.example.demo.service.UserService; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest @AutoConfigureMockMvc public class DeployBulkControllerTest { @Autowired private MockMvc mockMvc; @Autowired DeployBulkController dbc; @Autowired UserRepository rep; @Autowired DeploymentRepository rep2; @Autowired UserService us; @Autowired HttpSession ses; @Before public void setup() { mockMvc = MockMvcBuilders.standaloneSetup(dbc).build(); } @Test public void viewTest() throws Exception { //getのテスト ArrayList<UserEntity> empList = rep.findEmpByDeleteFlag(); ArrayList<UserForm> empForm = us.userList(empList); ArrayList<DeploymentEntity> depList = rep2.findDeploymentByDeleteFlag(); String empDemo = empForm.get(0).getName(); String depDemo = depList.get(0).getDeployment_name(); mockMvc.perform(get("/bulk")) .andExpect(status().isOk()) .andExpect(view().name("bulkRegistration")) .andExpect(model().attribute("title", "部署一括登録")); assertThat(empDemo, is("山田太郎")); assertThat(depDemo, is("ITソリューション部")); } @Test public void bulkRegistrationDeployTest() throws Exception { mockMvc.perform(post("/depBulkRegister").params(uf, new String[] { "bob", "margret" })) .andExpect(model().hasErrors()) .andExpect(model().attribute()) .andExpect(redirectedUrl("/depTop")); } }

UserForm

1package com.example.demo.form; 2 3public class UserForm { 4 5 private int id; 6 private String name; 7 private String phonetic; 8 private String mail; 9 private String deployment; 10 private int initialization_flag; 11 private int delete_flag; 12 private String password; 13 private int sort_num; 14 private int identify; 15 16 public int getId() { 17 return id; 18 } 19 20 public void setId(int id) { 21 this.id = id; 22 } 23 24 public String getName() { 25 return name; 26 } 27 28 public void setName(String name) { 29 this.name = name; 30 } 31 32 public String getPhonetic() { 33 return phonetic; 34 } 35 36 public void setPhonetic(String phonetic) { 37 this.phonetic = phonetic; 38 } 39 40 public String getMail() { 41 return mail; 42 } 43 44 public void setMail(String mail) { 45 this.mail = mail; 46 } 47 48 public String getDeployment() { 49 return deployment; 50 } 51 52 public void setDeployment(String deployment) { 53 this.deployment = deployment; 54 } 55 56 public int getInitialization_flag() { 57 return initialization_flag; 58 } 59 60 public void setInitialization_flag(int initialization_flag) { 61 this.initialization_flag = initialization_flag; 62 } 63 64 public int getDelete_flag() { 65 return delete_flag; 66 } 67 68 public void setDelete_flag(int delete_flag) { 69 this.delete_flag = delete_flag; 70 } 71 72 public String getPassword() { 73 return password; 74 } 75 76 public void setPassword(String password) { 77 this.password = password; 78 } 79 80 public int getSort_num() { 81 return sort_num; 82 } 83 84 public void setSort_num(int sort_num) { 85 this.sort_num = sort_num; 86 } 87 88 public int getIdentify() { 89 return identify; 90 } 91 92 public void setIdentify(int identify) { 93 this.identify = identify; 94 } 95 96} 97

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

A-pZ

2020/08/28 05:26

Controllerから実行するServiceクラスやRepositoryクラスがMockになっていないのですが、これは実体を動かしたい(=実際にDBへ更新を行いたい)テストなのでしょうか…?(単体試験ではこのように書きません…)
soso0programmer

2020/08/31 03:55

返信遅れて大変申し訳ありません。 本来であれば実体を動かすようなテストではないのですが、納期までの時間がなく、データベースとつなげてデータベースの内容をもとにテストにすることになりました。 その場合、mockmvcは使わないのでしょうか?
A-pZ

2020/08/31 09:22

実体が動いてしまう場合はデータベースの状態によってテストクラスが期待する挙動が変わってしまうのでテストコードは単なるControllerを起動するクラスになりますので、あまり良い状態ではありません。 Controllerの単体試験はControllerとControllerから呼び出すServiceクラスをMockにして、その挙動を試験させた方が単体試験として有用です。
soso0programmer

2020/09/01 04:24

回答ありがとうございます。 ControllerとServiceクラスをMockにして挙動を試験させるのが一般的なのですね。 今後の単体テストの際に、その部分を意識していきたいと思います。 重ね重ねありがとうございました。
A-pZ

2020/09/01 04:59

あ、語弊を生んでしまいました、すみません。Controllerの単体テストは、Serviceをモックにして、が正確でした。失礼いたしました。
guest

回答1

0

自己解決

mockmvcではArraylistで渡ってくるデータをテストすることができなかったので、formで受け取る形にし、param値を設定する(param="")ことで、mockmvcのparamメソッドでテストをすることはできました。

投稿2020/09/02 07:44

soso0programmer

総合スコア35

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問