How to enforce MockitoJUnitRunner fail without bas

2020-04-16 06:33发布

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条回答
贼婆χ
2楼-- · 2020-04-16 07:01

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

查看更多
登录 后发表回答