1

MockMvcMockitoJUnitRunnerを使用して@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); 
} 

答えて

1

SpringJUnit4ClassRunnerの目的は、自動的にアプリケーションCをロードすることですontextを実行し、自動的にすべてを上げます。 MockitoJUnitRunnerを使用できるはずですが、テストで手動で使用するアプリケーションコンテキストをロードする必要があります。しかし、DataController#add()をSpring経由で呼び出すことが@Valid注釈が処理される唯一の方法であるため、アプリケーションコンテキストを読み込む必要はありません。

EDIT:実際の問題がJPAリポジトリをロードしている場合は、MockitoJUnitRunnerを使用して、偽のJPAリポジトリが手作業で接続されているテストアプリケーションのコンテキストをわずかにロードするだけです。

+0

'@Autowired(required = false)'を設定しない限り、 '@ Valid'アノテーションを処理するアプリケーションコンテキストをどのように作成するのかは分かりませんが、JPAリポジトリの欠落については不平を言いません。 – Arthur

+0

'@ Valid'アノテーションは、囲むクラスがテストクラスに配線されているか、テストクラスによってアプリケーションコンテキストから取得されている限り、テストされます。いくつかのサンプルコードが必要な場合は教えてください。 – entpnerd

+0

大きな問題でなければ、例を挙げてください。 – Arthur

関連する問題