How to enforce MockitoJUnitRunner fail without basic http authentication?

风流意气都作罢 提交于 2020-01-11 11:23:09

问题


I write a Spring Boot app and I was able to access and test Controller with MockMvc. The issue is that during testing security is not enforced and I can access Controller with no user.

Am I doing anything wrong? Is it intended behavior?

ControllerTest class:

@RunWith(MockitoJUnitRunner.class)
public class ControllerTest {

    private MockMvc mockMvc;

    @Mock
    private Service service;

    @InjectMocks
    private Controller controller;

    private final static String URL = "/test";

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

    @Test
    public void test() throws Exception {
        mockMvc.perform(get(URL))
        .andExpect(status().isOk());
    }

}

My SecurityConfig StackOverflow QA.


回答1:


Your examples uses a plain unit test to test your controller. In this setup the Controller is created by Mockito (the controller field is annotated with Mockito's @InjectMocks).

Mockito is not aware of Spring, in consequence no Spring Security will be setup in your test.

You need to use the SpringRunner to run your test. This runner is Spring aware and allows you to properly initialize your controller before the test is run.

The test should look something like this (junit5):

@ExtendWith(SpringExtension.class)
@WebMvcTest(controllers = Controller.class)
public class ControllerTest {
  @Autowired
  private MockMvc mockMvc;

  @MockBean
  private Service serviceMock;

   @Test
    public void test() throws Exception {
        mockMvc.perform(get(URL))
        .andExpect(status().isOk());
    }

}

check our the Spring documentation or some tutorials for further information

  • https://spring.io/guides/gs/testing-web/

  • https://docs.spring.io/spring/docs/current/spring-framework-reference/testing.html



来源:https://stackoverflow.com/questions/58401388/how-to-enforce-mockitojunitrunner-fail-without-basic-http-authentication

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!