Testowanie kontrolera za pomocą Mockito

0

Witam, uczę się testów juiit i mockito. Stoję przed problemem takim, że nie test się mi nie wykrzacza, możliwe, że coś zle konfiguruje w springu.. próbuję przetestować kontroler.
Struktura projektu:
screenshot-20170408173058.png

WebbAppContext .java :

package com.cand.source.webconfig;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class WebbAppContext extends AbstractAnnotationConfigDispatcherServletInitializer {
      
	@Override
	protected Class<?>[] getRootConfigClasses() {
		return new Class<?>[] {RootConfig.class};
	}

	@Override
	protected Class<?>[] getServletConfigClasses() {
		
		return new Class<?>[] {WebConfig.class};
	}

	@Override
	protected String[] getServletMappings() {
		return new String[]{"/"};
	}
}

RootConfig.java w książce napisano, że do tego konfigurację można pominąć:

package com.cand.source.webconfig;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration
@ComponentScan(basePackages ={"com.cand.source"}, excludeFilters={@Filter(type=FilterType.ANNOTATION, value = EnableWebMvc.class)})
public class RootConfig {

}

WebConfig.java:

package com.cand.source.webconfig;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@EnableWebMvc
@ComponentScan({"com.cand.source.controllers", "com.cand.tests"})
public class WebConfig extends WebMvcConfigurerAdapter {

	@Bean
	public ViewResolver viewResolver(){
		InternalResourceViewResolver resolver = new InternalResourceViewResolver();
		resolver.setPrefix("/WEB-INF/views/");
		resolver.setSuffix(".jsp");
		resolver.setExposeContextBeansAsAttributes(true);
		return resolver;
		
		}
	@Override
	public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
		configurer.enable();
	}
}

HomeController

package com.cand.source.controllers;

import org.junit.runner.RunWith;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


@Controller
public class HomeController {

	@RequestMapping(value = "/", method= RequestMethod.GET)
	public String showHome(){
		return "home";
	}
}

No i na koniec mój test:

  1. w miejscu MockMvcResultMatchers.view().name("hom2e") powinno się wykrzaczyć, bo kontroler zwraca "home", zamiast "hom2e".
  2. to są moje pierwsze kroki z testami, breakpoint się zatrzymuje w metodzietestHomePage() i wszystkie linie się wykonują.
  3. @ContextConfiguration co w zasadzie powinno się podawać tutaj w adnotacji w tym przypadku?
package com.cand.tests;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import com.cand.source.controllers.HomeController;
import com.cand.source.webconfig.WebbAppContext;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {WebbAppContext.class})
public class HomeControllerTest{

	@Test
	public void testHomePage() throws Exception{
		HomeController controller = new HomeController();
		MockMvc mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
		mockMvc.perform(MockMvcRequestBuilders.get("/")).andExpect(MockMvcResultMatchers.view().name("hom2e"));
	}
}

Odpalam testy za pomocą
screenshot-20170408174033.png
Konsola po odpaleniu:

kwi 08, 2017 5:28:32 PM org.springframework.test.context.support.DefaultTestContextBootstrapper getDefaultTestExecutionListenerClassNames
INFO: Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
kwi 08, 2017 5:28:32 PM org.springframework.test.context.support.DefaultTestContextBootstrapper instantiateListeners
INFO: Could not instantiate TestExecutionListener [org.springframework.test.context.transaction.TransactionalTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [org/springframework/transaction/interceptor/TransactionAttributeSource]
kwi 08, 2017 5:28:32 PM org.springframework.test.context.support.DefaultTestContextBootstrapper instantiateListeners
INFO: Could not instantiate TestExecutionListener [org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [org/springframework/transaction/interceptor/TransactionAttribute]
kwi 08, 2017 5:28:32 PM org.springframework.test.context.support.DefaultTestContextBootstrapper getTestExecutionListeners
INFO: Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@71be98f5, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@6fadae5d, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@17f6480, org.springframework.test.context.support.DirtiesContextTestExecutionListener@2d6e8792]
kwi 08, 2017 5:28:32 PM org.springframework.context.support.GenericApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.GenericApplicationContext@59e84876: startup date [Sat Apr 08 17:28:32 CEST 2017]; root of context hierarchy
kwi 08, 2017 5:28:32 PM org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StaticRequestMappingHandlerMapping register
INFO: Mapped "{[/],methods=[GET]}" onto public java.lang.String com.cand.source.controllers.HomeController.showHome()
kwi 08, 2017 5:28:33 PM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter initControllerAdviceCache
INFO: Looking for @ControllerAdvice: org.springframework.test.web.servlet.setup.StubWebApplicationContext@6a396c1e
kwi 08, 2017 5:28:33 PM org.springframework.mock.web.MockServletContext log
INFO: Initializing Spring FrameworkServlet ''
kwi 08, 2017 5:28:33 PM org.springframework.test.web.servlet.TestDispatcherServlet initServletBean
INFO: FrameworkServlet '': initialization started
kwi 08, 2017 5:28:33 PM org.springframework.test.web.servlet.TestDispatcherServlet initServletBean
INFO: FrameworkServlet '': initialization completed in 3 ms
kwi 08, 2017 5:28:33 PM org.springframework.context.support.GenericApplicationContext doClose
INFO: Closing org.springframework.context.support.GenericApplicationContext@59e84876: startup date [Sat Apr 08 17:28:32 CEST 2017]; root of context hierarchy

Struktura projektu jest trochę zmieniona bo robię to na Mavenie zamiast Gradle oraz w Eclipse zamiast Inteliji- póki co chce ogarnac Eclipse ;)

0

Dobra, już wiem ;) wszystko jest ok, tylko w konsoli nie wyświetla błędów... natomiast wyświetli je w
screenshot-20170408180901.png

0
  1. Zamień Eclipsa na IntelliJ
  2. Testuj Integracyjnie z użyciem webowego contextu (endpointowo)
0

@scibi92: mógłbyś rozwinąć punkt drugi? webowy, czyli który? i jak endpointowo? testowy laik ze mnie :)

0

Stawiasz cały kontekst Springa z danymi/zależnościami jak najbardziej zbliżonymi do produkcyjnych i wtedy testujesz, w twoim wypadku czy zwróci poprawny widok.
Dwa linki dot. testowania Spring Boota, ale konfiguracja powinna być podobna. To odpowiedni kierunek

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-testing-spring-boot-applications-testing-autoconfigured-mvc-tests
https://blog.jayway.com/2014/07/04/integration-testing-a-spring-boot-application/

1 użytkowników online, w tym zalogowanych: 0, gości: 1