I am tring to write test for spring mvc controller. In view of the controller use validator which need bean injection I cannot use MockMvcBuilders.standaloneSetup bacause in this case spring refuses make injection into validator (possibly there is a way kindky ask it makes injection into validator despite standaloneSetup but I do not how to do it). Therefore I made changes in my test setting and substitute standaloneSetup on webAppContextSetup. This action solve problems with injection in validator but new problem appeared. My service, which is used by controller, does not mocking anymore. Test uses real service class and it's lead to real changes in DB (in my case, service save entity into DB).
How to solve this issue?
Test
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring-context.xml"})
@TestPropertySource("classpath:test-local.properties")
@ActiveProfiles(profiles = "test")
@WebAppConfiguration
public class ClientControllerTest {
private MockMvc mockMvc;
@Mock
ClientService clientService;
@InjectMocks
ClientController clientController;
@Autowired
private WebApplicationContext webApplicationContext;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
when(clientService.saveClient(Matchers.<Client>anyObject())).thenReturn(new Long(1));
}
@Test
@Transactional
@Rollback(true)
public void addClient_Post_formIsValid_ClientHaveToBeSaved_Test() throws Exception {
String name = "ivanov";
String phoneNumber = "";
Boolean isPayByCash = true;
Integer priceMultiplicator = new Integer(100);
mockMvc.perform(post("/owner/client/add")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("name", name)
.param("phoneNumber", phoneNumber)
.param("isPayByCash", isPayByCash.toString())
.param("priceMultiplicator", priceMultiplicator.toString()))
.andExpect(status().isFound())
.andExpect(view().name("redirect:/owner/client/all"))
.andExpect(redirectedUrl("/owner/client/all"))
.andExpect(flash().attribute("globalMsg", "Client + " + name + " was created successfully (#" + 1 + ")"));
}
}
Aucun commentaire:
Enregistrer un commentaire