MockMvc
とMockitoJUnitRunner
を使用して@Valid
注釈をテストすることはできますか?私はCRUDコントローラの動作の大部分をテストできますが、バリデーションにはSpringのJUnitランナーを使用し、コンテキスト全体を構築し、多くのものを必要とするJPAレポ実装を作成する必要があるようです。MockMvcによるフィールド検証のユニットテストで、Springコンテキストはありませんか?
firstName
フィールドに@Size(min=2, max=20)
と注釈されたCustomer
エンティティを受信するPOSTメソッドをテストしようとするテストです。結果は
java.lang.AssertionError: View name expected:<edit> but was:<redirect:/info>
です。したがって、検証は実行されませんでした。
@RunWith(MockitoJUnitRunner.class)
public class DataControllerTest {
@Mock
CustomerRepository mockRepo;
@InjectMocks
private DataController controller;
MockMvc mockmvc;
@Before
public void init() {
MockitoAnnotations.initMocks(this);
mockmvc = MockMvcBuilders.standaloneSetup(controller).build();
}
@Test
public void testBadSubmit() throws Exception {
mockmvc.perform(MockMvcRequestBuilders.post("/edit/1")
.param("firstName", "a"))
.andExpect(MockMvcResultMatchers.view().name("edit"));
Mockito.verifyZeroInteractions(mockRepo);
}
}
コントローラクラス:
@Controller
public class DataController {
@Autowired
public CustomerRepository crep;
...
@RequestMapping(value = {"/edit/{id}"}, method = RequestMethod.POST)
public String add(Model model, @Valid Customer customer, Errors result) {
if (result.hasErrors()) {
return "edit";
}
crep.save(customer);
return "redirect:/info";
}
エンティティ:
@Entity
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id = null;
@Column(length=20)
@Size(min=2, max=20)
private String firstName;
...
}
JPAリポジトリインターフェース:
@Repository
public interface CustomerRepository extends JpaRepository<Customer, Long> {
List<Customer> findByLastName(String lastName);
}
'@Autowired(required = false)'を設定しない限り、 '@ Valid'アノテーションを処理するアプリケーションコンテキストをどのように作成するのかは分かりませんが、JPAリポジトリの欠落については不平を言いません。 – Arthur
'@ Valid'アノテーションは、囲むクラスがテストクラスに配線されているか、テストクラスによってアプリケーションコンテキストから取得されている限り、テストされます。いくつかのサンプルコードが必要な場合は教えてください。 – entpnerd
大きな問題でなければ、例を挙げてください。 – Arthur