R&D人材として、あなたは自分のコードをテストして喜んでいるかどうか、各企業の技術部門があるため、より、品質管理のニーズに理由の一部である理由である、品質保証の開発のためのテストの重要性を認めざるを得ませんでしたバグは、環境製品版は、すべてで最もコストのバグを見つけ、コードの低コストは、例えば、見つかったのDev環境のバグが環境QAのコストよりも低くなって、見つかったQA環境のバグがprod環境のコストよりも低くなって、早期に発見されましたほとんどの開発者が遭遇したくないが、永遠に現実を避けるために余裕はありません。
それは完全に回避することはできませんが、我々は十分に自分のコードをテストすることができますが、発生した不具合の可能性を減らします。
だから、このブログ私たちは主のSpring MVCコントローラの下の試験方法の三種類に:
- 展開プロジェクトのテストの後
- JUnitのテストフレームワークとSpringテストと
- SwaggerUIインタフェースのドキュメントテストと
1.テストの後にプロジェクトを展開
2は前回のブログでは、我々が取るこの方法をテストすることです、プロジェクトはすぐに、Tomcatにデプロイする、戦争のパッケージとしてラベル付けされる、などのブラウザやポストマンテストコントローラなどのツールを使用して、プロジェクトを実行します。
あなたが要求を取得した場合は、ブラウザやポストマンテストを使用することができます。
ポストは、入れた場合は、削除し、その要求に応じて、ポストマンを使用して試験することができます。
興味のある学生は、前の二つのブログで見ることができます:
春スターター(XII):春のMVCを説明するために使用します
春スターター(XIII):Spring MVCのは、一般的にコメントを説明するために使用します
JUnitテストフレームワークとSpringテスト2.
上記の方法をテストすることができますが、しかし、それぞれのパッケージ、展開、プロジェクト、テストを実行し、明らかに不便はなく、統合テストをサポートするための強力な春春のテストフレームワークを提供することで、我々は特定の用途を説明します。
春のそれのプロジェクトのディレクトリ構造は、次の4種類がありますので、私たちのプロジェクトは、Mavenのによって管理されているので:
- SRC /メイン/ javaの:商品コード
- SRC /メイン/リソース:リソースプロジェクト
- SRC /テスト/ javaの:テストコード
- SRC /テスト/リソース:テスト・リソース(デフォルトのディレクトリが生成されていない、独自の新が必要な場合があります)
言い換えれば、我々はSRC /テスト/ javaディレクトリの下に我々のテストコードを置くことができますが、今まで、私たちは、ディレクトリ内の任意のテストコードを追加しませんでした。
2.1依存関係を追加します。
テストコードを追加する前に、我々はのpom.xmlに以下の依存関係を追加する必要があります。
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.18.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
おそらく、一部の学生は不思議、なぜこの依存増加を追加<scope>test</scope>
するので、どのような役割は、それをしませんか?
この質問では、我々は実際に与えられている通常のコンパイルされたコードコンパイラで発見された、プロジェクトでコンパイル:
これはなぜそれがありません、と、エラーメッセージがorg.junitが存在しないパッケージを要求しますが、我々は明らかに依存ああを追加している<scope>test</scope>
かについて?
おめでとう、あなたはそれを推測し、実際に<scope>test</scope>
この時点では、プロジェクトは、コンパイラを与えられていない(されて削除される場合には、関連するが、削除することを推奨しません)。
これは、我々の前にテストコードに追加したので、src / main / javaディレクトリの下に置かれている今、依存パッケージの増加で<scope>test</scope>
、これらのパッケージの生存期間は、テストサイクルであることを示す、ので、私たちは前にコードをテストすることができます下のsrc /テスト/ javaディレクトリに、次のように:
コンパイラが見つけ、再度プロジェクトをビルドします。
2.2コントローラの追加
コントローラを追加する前に、などの新しいDemoServiceは次のとおりです。
package chapter05.service;
import org.springframework.stereotype.Service;
@Service
public class DemoService {
public String saySomething() {
return "hello";
}
}
注意:このクラスは、@Serviceコメントを追加します。
その後、新しいコントローラNormalControllerは、この方法は、その内部のビューJSPに戻します。
package chapter05.controller;
import chapter05.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class NormalController {
@Autowired
private DemoService demoService;
@RequestMapping("/normal")
public String testPage(Model model) {
model.addAttribute("msg", demoService.saySomething());
return "page";
}
}
次いで、新しいコントローラMyRestController、その内部の方法は、情報を返します。
package chapter05.controller;
import chapter05.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyRestController {
@Autowired
private DemoService demoService;
@RequestMapping(value = "/testRest", produces = "text/plain;charset=UTF-8")
public String testRest() {
return demoService.saySomething();
}
}
2.3テストコードを追加します
新しいパッケージchapter05下のsrc /テスト/ Javaでは、新しいテストクラスTestControllerIntegrationTestsその下に次のように:
package chapter05;
import chapter05.config.MyMvcConfig;
import chapter05.service.DemoService;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {MyMvcConfig.class})
@WebAppConfiguration("src/main/resources")
public class TestControllerIntegrationTests {
private MockMvc mockMvc;
@Autowired
private DemoService demoService;
@Autowired
private WebApplicationContext webApplicationContext;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build();
}
}
説明するコード:
@RunWith(SpringJUnit4ClassRunner.class)
JUnitの環境で機能を提供するための春のテストフレームワーク。
@ContextConfiguration(classes = {MyMvcConfig.class})
属性は次のようにクラスの設定クラス、MyMvcConfigの設定クラスのコードをロードするために使用されている設定のApplicationContextをロードするために使用します:
package chapter05.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
/**
* Spring MVC配置
*/
@Configuration
@EnableWebMvc
@ComponentScan("chapter05")
public class MyMvcConfig {
/**
* 视图解析器配置
*
* @return
*/
@Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/classes/views/");
viewResolver.setSuffix(".jsp");
viewResolver.setViewClass(JstlView.class);
return viewResolver;
}
}
@WebAppConfiguration("src/main/resources")
用来声明加载的ApplicationContext是一个WebApplicationContext,它的属性指定的是Web资源的位置,默认为src/main/webapp,这里我们修改成
src/main/resources。
MockMvc用来模拟Mvc对象,它在添加了@Before
注解的setup()中,通过this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build();
进行初始化赋值。
然后往测试类中添加如下测试代码:
@Test
public void testNormalController() throws Exception {
mockMvc.perform(get("/normal"))
.andExpect(status().isOk())
.andExpect(view().name("page"))
.andExpect(forwardedUrl("/WEB-INF/classes/views/page.jsp"))
.andExpect(model().attribute("msg", demoService.saySomething()));
}
代码解释:
perform(get("/normal"))
用来模拟向/normal发起get请求,
andExpect(status().isOk())
预期返回的状态码为200,
andExpect(view().name("page"))
预期视图的逻辑名称为page,
andExpect(forwardedUrl("/WEB-INF/classes/views/page.jsp"))
预期视图的真正路径是/WEB-INF/classes/views/page.jsp",
andExpect(model().attribute("msg", demoService.saySomething()))
预期Model里有一个msg属性,它的值是demoService.saySomething()
的返回值hello。
执行该测试方法,测试通过:
最后往测试类中添加如下测试代码:
@Test
public void testRestController() throws Exception {
mockMvc.perform(get("/testRest"))
.andExpect(status().isOk())
.andExpect(content().contentType("text/plain;charset=UTF-8"))
.andExpect(content().string(demoService.saySomething()));
}
代码解释:
perform(get("/testRest"))
用来模拟向/testRest发起get请求,
andExpect(status().isOk())
预期返回的状态码为200,
andExpect(content().contentType("text/plain;charset=UTF-8"))
预期返回值的媒体类型为text/plain;charset=UTF-8,
andExpect(content().string(demoService.saySomething()))
预期返回值的内容为demoService.saySomething()
的返回值hello。
执行该测试方法,测试通过:
3. 源码及参考
源码地址:https://github.com/zwwhnly/spring-action.git,欢迎下载。
Craig Walls 《Spring实战(第4版)》
汪云飞《Java EE开发的颠覆者:Spring Boot实战》
4. 最后
欢迎扫码关注微信公众号:「申城异乡人」,定期分享Java技术干货,让我们一起进步。