2016-07-14 98 views
0

我想为Controller类创建一个Spring Boot测试。测试Spring Boot应用程序?

我想要测试的方法是:

private String statusQueryToken; 

@RequestMapping("/onCompletion") 
public String whenSigningComplete(@RequestParam("status_query_token") String token){ 
    this.statusQueryToken = token; 

我不确定如何在春季启动测试的东西。

如果我想测试字段statusQueryToken已使用@RequestParam("status_query_token")初始化,我该如何去做这件事?

谢谢!

+2

* “我不确定如何在春季启动测试的东西。” * - 你的意思是*之前*或* *后读[文件](HTTP://docs.spring。 IO /弹簧引导/文档/ 1.4.0.RC1 /参考/ htmlsingle /#引导功能测试)? – kryger

回答

5

你可以使用Spring MockMvc

因此,尝试这样的事:

MockMvc mockMvc = MockMvcBuilders.standaloneSetup(controller).build(); 
mockMvc.perform(get("/onCompletion").param("status_query_token", "yourToken")) 
       .andExpect(status().isOk()); 
0

有不同的方法来测试

1.使用Maven

$ mvn clean install 

这会生成默认情况下,嵌入的Tomcat与春天启动的jar文件

$ mvn spring-boot:run 

这将运行你的应用程序春天

现在春天是启动和运行

2.创建一个可执行的JAR(在没有Maven的)

$ java -jar target/myproject.0.0.1.SNAPSHOT.jar 

“如上述相同的效果”

现在打开浏览器或SOAP UI或小提琴手或邮政局长发送请求到控制器

例如:GET方法 http://localhost:8080/myproject/onCompletion/hello

http://docs.spring.io/spring-boot/docs/current/reference/html/getting-started-first-application.html

+0

您正在描述如何运行应用程序,而不是如何测试应用程序。 – kryger

2

有可以处理这个几个方法。我最喜欢用真正的tomcat实例进行测试。

@RunWith(SpringJUnit4ClassRunner.class) 
    @WebIntegrationTest("server.port:0") 
    @SpringApplicationConfiguration(YourMainApplication.class) 
    public class TestClass() { 
     @Value("${local.server.port}") 
     private int port; 
    @Autowired 
    private RestTemplate restTemplate; 

    public <T> T get(String path, Class<T> responseType, Object... pathVariables) { 
     return restTemplate.getForEntity(path, responseType, pathVariables).getBody(); 
    } 

    } 
+0

使用Spring的MockMvc是一个更好的解决方案,请参阅@SergheyBishyr答案,并将其标记为接受的答案,如果您确信 – Matt

+1

正如我所说的那样,有几种方法可以做到这一点,但我更愿意在真实服务器实例上进行测试,而不是伪造请求和响应,但这一切都取决于要求。 – krmanish007

0
@RunWith(MockitoJUnitRunner.class) 
@SpringBootTest(classes = ApplicationConfiguration.class) 
public class ItemFeedTest { 

@InjectMocks 
private PersonRepository personRepository; 


@Autowired 
@Mock 
private PersonService personService; 


@Before 
    public void setup() throws IOException { 
     MockitoAnnotations.initMocks(this); 
    } 

@Test 
    public void onSuccessTest() { 
     //Write the Junit Test and mock the required Class 
} 

} 
相关问题