我想測試一個Spring Boot
其餘的控制器,它使用Spring security
進行保護,並在其中使用模擬。我曾嘗試過Mockito,但我認爲任何嘲弄工具都應該做到這一點。Spring MockMVC,Spring security and Mockito
爲了使春季安全測試中,我第一次做如下:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Main.class)
@TestPropertySource(value="classpath:application-test.properties")
@WebAppConfiguration
@ContextConfiguration
public class MyTest{
protected MockMvc mockMvc;
@Autowired
private WebApplicationContext wac;
@Before
public void setUp(){
mockMvc = MockMvcBuilders
.webAppContextSetup(wac)
.apply(SecurityMockMvcConfigurers.springSecurity())
.build();
}
@Test
public void doTheTest(){
mockMvc.perform(post("/user/register")
.with(SecurityMockMvcRequestPostProcessors.csrf())
.content(someContent()));
}
}
直到有,它工作得很好。
經過這一步之後,我希望添加mock來隔離測試我的安全控制器。
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Main.class)
@TestPropertySource(value="classpath:application-test.properties")
@WebAppConfiguration
@ContextConfiguration
public class MyTest{
protected MockMvc mockMvc;
@Mock
private Myservice serviceInjectedInController;
@InjectMocks
private MyController myController;
@Autowired
private WebApplicationContext wac;
@Before
public void setUp(){
mockMvc = MockMvcBuilders
.webAppContextSetup(wac)
.apply(SecurityMockMvcConfigurers.springSecurity())
.build();
}
@Test
public void doTheTest(){
mockMvc.perform(post("/user/register")
.with(SecurityMockMvcRequestPostProcessors.csrf())
.content(someContent()));
}
}
不幸的是,嘲笑的服務未在控制器注入,因爲沒有涉及的MockMVC和嘲笑什麼,所以嘲笑不會在控制器注入。
所以我試圖改變MockMVC的配置,如下所示:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Main.class)
@TestPropertySource(value="classpath:application-test.properties")
@WebAppConfiguration
@ContextConfiguration
public class MyTest{
protected MockMvc mockMvc;
@Mock
private Myservice serviceInjectedInController;
@InjectMocks
private MyController myController;
@Before
public void setUp(){
mockMvc = MockMvcBuilders
.standAloneSetup(myController)
.apply(SecurityMockMvcConfigurers.springSecurity())
.build();
}
@Test
public void doTheTest(){
mockMvc.perform(post("/user/register")
.with(SecurityMockMvcRequestPostProcessors.csrf())
.content(someContent()));
}
}
但在這種情況下,我有另外一個問題。春季安全是抱怨的配置:
java.lang.IllegalStateException: springSecurityFilterChain cannot be null. Ensure a Bean with the name springSecurityFilterChain implementing Filter is present or inject the Filter to be used.
我沒有其他的想法,使安全和嘲笑。任何想法?或者我應該採取另一種方式?
謝謝。
您使用Spring Security的4+版本:可以用明確提供springSecurityFilterChain? – Ritesh
我使用的是Spring-boot 1.2.7.RELEASE,我已經覆蓋默認的Spring安全性來使用4.0.2 –
@Remi你有沒有解決這個問題? – hvgotcodes