使用Spring-data转换器时,使用Mocks测试控制器

时间:2015-12-16 12:17:19

标签: spring unit-testing junit mockito spring-data-jpa

我想测试BookFormController我的addBook表格。我想模拟我使用的每个服务,一切似乎都运行良好,但问题是我的POST方法基于spring-data转换器从{id}生成Author对象和Type对象。

现在我想我想以某种方式嘲笑那些转换器,所以当我传递author =“1”时,它应该将书籍作者转换为某个对象,以便我对作者和NotNullNotEmpty进行验证。类型已通过。

Book.class:

public class Book extends Item {

    @ManyToOne
    @JoinColumn(name = "author_id")
    @NotNull
    private Author author;

Items.class

@NotEmpty
@Column(nullable = false)
private String isbn;

@NotEmpty
@Column(nullable = false)
private String title;

@Column(name = "page_number", nullable = false)
@Min(1)
@NotNull
private Integer pageNumber;

@DateTimeFormat(iso = ISO.DATE)
@Column(name = "release_date", nullable = false)
@NotNull
private LocalDate releaseDate;

@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "items_types", joinColumns = {
        @JoinColumn(name = "item_id", referencedColumnName = "id") }, inverseJoinColumns = {
                @JoinColumn(name = "type_id", referencedColumnName = "id") })
@NotEmpty
private Set<Type> types = new HashSet<>();

@OneToMany(mappedBy = "item", cascade = { CascadeType.REMOVE })
private List<Borrow> borrows;

BookFormController POST方法:

@RequestMapping(value = "/add", method = RequestMethod.POST)
public String addBookAction(@Valid @ModelAttribute("book") Book book, BindingResult result, Model model,
            RedirectAttributes redirectAttributes) {
        if (result.hasErrors()) {
            return "book/bookForm";
        }
        bookService.save(book);
        redirectAttributes.addFlashAttribute("messageCode", "BookAdd.message.successfull");
        return "redirect:/books";
    }

我的测试:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { WebConfig.class })
@WebAppConfiguration
public class BookFormControllerTest {

    private MockMvc mockMvc;

    @Mock
    private BookService bookService;

    @Mock
    private TypeService typeService;

    @Mock
    private AuthorService authorService;

    @InjectMocks
    private BookFormController bookFormController;

    @Before
    public void init() {
        MockitoAnnotations.initMocks(this);
        mockMvc = MockMvcBuilders.standaloneSetup(bookFormController).build();
    }

    @Test
    public void testAddBookPost() throws Exception {
        Mockito.doNothing().when(bookService).save(any(Book.class));
        mockMvc.perform(post("/books/add")
        .param("title", "Spring MVC")
        .param("isbn", "123QWE")
        .param("author", "1")
        .param("releaseDate", "2010-10-10")
        .param("pageNumber", "256")
        .param("types", "1")
        .param("types", "2"))
        .andExpect(status().is3xxRedirection())
        .andExpect(flash().attribute("messageCode", "BookAdd.message.successfull"))
        .andExpect(redirectedUrl("/books"));
    }

由于转换器,此测试无法正常工作。当我从book / items对象中删除NotNull和NotEmpty并且不在POST中发送这些值时,此测试有效。所以我该怎么做?

0 个答案:

没有答案