0

everyone. I am new to WebMvcTest, and am learning to write a PostControllerTest. While the project runs well, the test does not work.

2017-05-31 10:08:09.490  INFO 5768 --- [           main] nz.p2.controller.PostControllerTest      : Starting PostControllerTest on My-PC with PID 5768 (started by Me in C:\...)
2017-05-31 10:08:09.491  INFO 5768 --- [           main] nz.p2.controller.PostControllerTest      : No active profile set, falling back to default profiles: default
2017-05-31 10:08:10.989  INFO 5768 --- [           main] o.s.w.c.s.GenericWebApplicationContext   : Refreshing org.springframework.web.context.support.GenericWebApplicationContext@2a8d39c4: startup date [Wed May 31 10:08:10 NZST 2017]; root of context hierarchy
2017-05-31 10:08:12.788  INFO 5768 --- [           main] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2017-05-31 10:08:13.311  WARN 5768 --- [           main] o.s.w.c.s.GenericWebApplicationContext   : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'reCaptchaAuthenticationFilter': Unsatisfied dependency expressed through field 'reCaptchaService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'nz.p2.captcha.ReCaptchaService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
2017-05-31 10:08:13.326  INFO 5768 --- [           main] utoConfigurationReportLoggingInitializer : 

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-05-31 10:08:13.534 ERROR 5768 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Field reCaptchaService in nz.p2.captcha.ReCaptchaAuthenticationFilter required a bean of type 'nz.p2.captcha.ReCaptchaService' that could not be found.


Action:

Consider defining a bean of type 'nz.p2.captcha.ReCaptchaService' in your configuration.

It tells me to do something with the ReCaptchaService; which isn't used with the PostController. Given the simplifed Controller class:

@Controller
public class PostController {
  @Autowired
  private PostService postService;

  @RequestMapping(value = URI_POST_POST, method = RequestMethod.GET)
  public ModelAndView get(@Valid Long mkid) throws IOException {

    // do somthing here using postService;

    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName(URI_POST_POST);
    modelAndView.addObject("abc", abc);
    return modelAndView;
  }
}

The PostControllerTest class is here:

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = PostController.class)
public class PostControllerTest {  
  private MockMvc mockMvc;

  @Autowired
  private WebApplicationContext webApplicationContext;

  @MockBean
  private PostController postControllereMock;  

  @Before
  public void setUp() throws Exception {
    mockMvc = MockMvcBuilders.standaloneSetup(webApplicationContext).build();    
  }

  @Test
  public void testList() throws Exception {
    assertThat(this.postControllereMock).isNotNull();
    mockMvc.perform(MockMvcRequestBuilders.get(URI_POST_POST + "?mkid=8044022272730561994"))
            .andExpect(status().isOk())
            .andExpect(content().contentType("text/html;charset=UTF-8"))
            .andExpect(view().name(URI_POST_POST))
            .andExpect(MockMvcResultMatchers.view().name(URI_POST_POST))
            .andExpect(content().string(Matchers.containsString("I have put together some image galleries")))
            .andDo(print());
    }
}

I have to mention that the reCaptchaService is @Autowired in the ReCaptchaAuthenticationFilter, and the latter one is @Autowired and used here:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.
        // tl; nw
        .and().csrf().disable()
        .addFilterBefore(reCaptchaAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
        // tl; nw
  }
}

So, in this case, how can I test the PostController?

Leo.W
  • 539
  • 1
  • 7
  • 18
  • Sorry, should be "Hello, everyone." But the "Hello" does not show for some reason. – Leo.W May 30 '17 at 23:03
  • Your test is way to complex. Do you want to use `@WebMvcTest` or not, as you are trying very hard not to. Remove `@MockBean` for the `PostController`, place `@Autowired` on `MockMvc` and remove your `@Before` method (you are basically fighting against `@WebMvcTest` instead of using it). Regarding your error it looks like your configuration isn't loading the recaptcha configuration. – M. Deinum May 31 '17 at 06:59
  • @M. Deinum. Thank you for you comment. I am following the "Testing the Spring MVC Slice" on this website: https://springframework.guru/unit-testing-spring-mvc-spring-boot-1-4-part-1/ . I will follow your suggestions and post the reselt here. Thank you once again. – Leo.W May 31 '17 at 08:04
  • @M. Deinum. I got the same error after having changed the code. I also tried to put an "@AutoConfigureMockMvc(secure=false)" before "public class PostControllerTest", and the same error appeared. – Leo.W May 31 '17 at 08:26
  • That is what I suggested in the last part of my comment that the configuration regarding your recaptchaservice isn't loaded. – M. Deinum May 31 '17 at 08:46
  • Yes, but the reCaptchaService runs well if not with the test. Now I want to test the controller ( and which does not use reCaptchaService), how to make the test work? – Leo.W May 31 '17 at 09:25

0 Answers0