はじめに
- 作成したテストコードは【spring boot security + DB認証を試した時のポイント】用です
コード
- 下記のコードはDBへの接続を行わなずにモックを使用した場合のテストコード
DemoControllerTest.java
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@ContextConfiguration
@WebAppConfiguration
public class DemoControllerTest {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext context;
@Autowired
private FilterChainProxy springSecurityFilterChain;
@InjectMocks
private DemoController demoController;
@MockBean
private UserRepository userRepository;
@Before
public void setUp() {
mockMvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity(springSecurityFilterChain))
.build();
}
@Test
public void testLoginOk() throws Exception {
// 正常系
String user = "user01";
UserModel userModel = new UserModel("user01", "ゆーざ01", "pass1", true);
doReturn(userModel).when(userRepository).selectByUser(user);
mockMvc.perform(formLogin("/login").user(user).password("pass1"))
.andExpect(status().isOk());
}
@Test
public void testLoginNg1() throws Exception {
// DBにユーザが存在しない場合テスト
String user = "user01";
UserModel userModel = null;
doReturn(userModel).when(userRepository).selectByUser(user);
mockMvc.perform(formLogin("/login").user(user).password("pass1"))
.andExpect(status().is3xxRedirection());
}
@Test
public void testLoginNg2() throws Exception {
// 有効フラグが無効になっている場合のテスト
String user = "user01";
UserModel userModel = new UserModel("user01", "ゆーざ01", "pass1", false);
doReturn(userModel).when(userRepository).selectByUser(user);
mockMvc.perform(formLogin("/login").user(user).password("pass1"))
.andExpect(status().is3xxRedirection());
}
}
- 下記のコードはDBへの接続を行い一連の動作確認する場合のテストコード
DemoControllerITTest.java
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@ContextConfiguration
@WebAppConfiguration
public class DemoControllerITTest {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext context;
@Autowired
private FilterChainProxy springSecurityFilterChain;
@Before
public void setUp() {
mockMvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity(springSecurityFilterChain))
.build();
}
@Test
public void test1() throws Exception {
// ルートへのアクセス時のテスト
mockMvc.perform(get("/"))
.andExpect(status().isOk())
.andExpect(view().name("home"));
}
@Test
public void testLoginOk1() throws Exception {
// ログイン画面の正常系テスト
mockMvc.perform(formLogin("/login").user("user01").password("pass"))
.andExpect(status().isOk());
}
@Test
public void testLoginNg1() throws Exception {
// ログイン画面の異常系テスト
mockMvc.perform(formLogin("/login").user("user01").password("pass1"))
.andExpect(status().is3xxRedirection());
}
}