问题
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