How to use Java unit test assistant to build and improve spring test efficiently?

SWTOR 2021-01-21 16:03:54
use java unit test assistant


Spring frame ( together with Spring Boot Together ) It's the most popular Java One of the enterprise software frameworks . Its use in mission critical applications means that its quality and safety are strictly reviewed .

before , We talked about How developers don't like unit testing , Despite its proven track record of improvement , And introduced in detail Parasoft Jtest How to provide a directive and automated test method for the unit test assistant of , Make testing not only easier to accept , And it's easier and more effective . In this article , I will continue with Spring Frame as the theme , towards You show how to use automated and guided testing in this important application framework .

test Spring The challenge of application

Spring Framework provides good support for integration testing , But set up test cases correctly , It takes a lot of manual coding . Build and maintain Spring Application testing brings a series of unique challenges to developers , Including the following

  • Must be right Spring The framework is initialized and configured
  • Applications often have dependencies on third-party libraries ( Persistent storage 、 External services, etc )
  • Applications usually use built-in Spring function , For conversation 、 Security 、 Messaging, etc . For rigid contact Spring For test developers , Setting up these features can be tricky
  • You need to configure the application's dependencies appropriately ( namely Bean

These challenges , In addition, it usually takes a lot of time to write a comprehensive and maintainable test suite , As a result, developers don't write enough tests , In turn, , This in turn leads to security holes 、 defects 、 Regression and a lot of headaches .

Parasoft Jtest Unit Test Assistant Can help you , It makes 、 Improve and maintain JUnit The process of testing becomes simpler and time-saving , So developers can quickly build good tests , And back to them More preferred things —— Write code .

Spring MVC The test framework

Spring The framework includes a testing framework , It makes the controller 、 Testing services and other components becomes easier . It includes configuration Spring Test container 、 call Controller Processing methods and the ability to verify behavior using custom assertions .

for One Spring MVC Examples of controllers

@Controller
public class TodoController { @Autowired
private TodoService service;
@GetMapping("/") public String findAll(Model model) {
List<Todo> todos = service.findAll();
model.addAttribute("todos", todos);
return "todo/list";
}
}

In this example , The controller implements a simple REST service , From the " To do list " Get items from the list . It depends on a TodoService, It contains business logic .

In order to test findAll Method , We need a JUnit test , It can do the following

  • stay Spring Configure the tested Controller and TodoController The dependent TodoService.
  • towards findAll The handler sends a valid request .
  • Verify the elements of the response , Include return values ("todo/list") and Model attribute "todos".

Again One Spring MVC Junit An example of testing might be this

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class TodoControllerTest {
@Autowired
TodoController controller;
@Autowired
TodoService todoService;
MockMvc mockMvc;
@Before
public void setup() {
mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
}
@Configuration
static class Config {
@Bean
public TodoController getTodoController() {
return new TodoController();
}
@Bean
public TodoService getTodoService() {
return new TodoService();
}
}
@Test
public void testFindAll() throws Exception {
mockMvc.perform(get("/")).andExpect(view().name("todo/list"));
}
}

The above example is a very simple test —— But there are still many “ Model ” Code to write , There's a lot to do . In this case , We use an internal Configuration Class is Spring Configure a controller and its services , And then use MockMvc Function to send a request to the handler . then , We use MockMvc Function to send a request to the handler method ( Use perform), And use andExpect Verify the name of the returned view .

What's wrong with the above test ? It's nothing —— But imagine a more complex controller approach , There are many ways to deal with , Take more parameters and produce more output . Writing tests takes more time , Especially if good test coverage is important . Besides , Most real tests require more configuration (XML Or class configuration 、 Conversation and environment 、 Safety, etc ).

Use Parasoft Jtest Generate Spring test

Parasoft Jtest The unit test assistant can help developers write in many ways Spring test

  1. Automatically and quickly generate Spring MVC Template code for testing
  2. Automatic generation of parametric tests , Improve test coverage
  3. Simulate dependencies , To isolate auxiliary methods and simplify testing
  4. Collect coverage data at run time and analyze the test process
  5. Suggestions for improving testing , And provide a quick fix

Automatically generate tests

stay Parasoft Jtest In the middle of Spring The test is very direct —— Just in your IDE Choose one for your controller in Spring processing method , And select a test creation action

choice Regular Spring or Parameterized Spring Will automatically generate templates for you Spring MVC test , Include Configuration class ( And all that your controller depends on Bean).mockMvc.perform Calls are also added , And is preconfigured to call the processing method that creates the test .Jtest The unit test assistant even added some example assertions , You can uncomment and configure .

Parasoft Jtest Support use XML Or class configuration generation test , By setting... In preferences "ContextConfiguration attributes for Spring tests " Options .

Simulate dependencies

Managing dependencies in unit testing is crucial , Because most of the complexity and work comes from isolating the unit under test .Jtest The unit test assistant uses... By default Mockito or PowerMockito To simulate dependencies ( If you don't want that , You can disable... In preferences ). simulation Dependencies allow the test to control these dependencies , Isolate handler methods from the rest of the application , In order to focus the testing on the handler . In our example handler ,findAll The method is in TodoService Called on —— If we use a real TodoService, We tested it effectively TodoController and TodoService. This may be what we want in integration testing , But it's not what you want in unit testing . Simulate... In the test TodoService.findAll Response , Let's focus our testing efforts on processing methods .

If you want to learn more about Spring In the test Information that simulates dependencies , Please read my next article 1.21.)

Spring Boot

because Spring Boot by Bean Provides simplified configuration , And additional test notes , So when the unit test assistant is you Has been detected in Spring Boot when , It generates slightly different tests . for example ,MockMvc It's automatic , Dependency use @MockBean To simulate , And use @SpringBootTest annotation .

Run tests and analyze results

You can use any normal JUnit The runner runs the generated tests .Parasoft Jtest Provides running JUnit And analysis test toolbar operation .

After the test runs , The test execution process is displayed , The unit test assistant will make suggestions to improve the test , And in IDE Middle Report

Provide handler method input

Handler methods are usually configured to accept paths 、 Query or other parameters as parameters of the method . To test MVC Handler method , have access to MockMvc To build the path / Any other parameters needed to query and call the method .

Jtest The unit test assistant automatically configures mockMvc.perform Call to call the handler method . A single parameter is shown as a local variable in the test ( Or parameters in parametric testing ), These parameters need to be configured for the test to run correctly .

for example ( Unit test assistant is abbreviated as UTA

@Test public void testGetPerson() throws Throwable { // When String id = ""; // UTA: Configure an appropriate parameter value since the tested method depends on it ResultActions actions = mockMvc.perform(get("/people/" + id));

here , Need configuration "id" character string —— without , So the path to use would be "/people/",Spring The path provided will not be matched to the appropriate processing method .

class="p1> The unit test assistant looks for various types of handler method parameters , And automatically prepare them for testing in the following ways

  • HttpSession( Add one more setAttribute() Example of invocation )
  • Head ( Add one more header() call )
  • Request body ( Add one payload Variables and content() call )
  • authentication ( stay setup Method , And one. principal() call )

Run a test that does not cause handler methods to be called , A suggestion similar to the following will arise :

Verify the output of the handler method

Depending on what the handler method provides to the caller , It can return multiple types . Most of the time , The handler returns a ModelAndView( Or something like that , Such as Model or RedirectView) To serve the page , Or return some kind of ResponseEntity( Sometimes it's just the original object to serialize ). This response can be accessed Spring MVC Test framework to verify .

for example ,Jtest The unit test assistant returns for a ModelAndView The following assertion is added to the handling of

 // When
String id = "1";
ResultActions actions = mockMvc.perform(get("/people/" + id));
// Then
// actions.andExpect(status().isOk());
// actions.andExpect(header().string("", ""));
// actions.andExpect(view().name(""));
// actions.andExpect(model().attribute("", ""));

Once the test is generated , You can uncomment these assertions and fill in the values , To quickly build a useful and valuable test . If an assertion fails at run time , The unit test assistant provides a suggestion and quick fix , To automatically update the expected value or simply delete the assertion . To quickly set a correct assertion value , You can uncomment the assertion , Let it fail , Then use quick fix to set the right expectations .

summary

Spring( combination Spring Boot) It's the leading enterprise class Java Application framework , So the right level of testing is needed , To ensure the quality and security of the applications built with it . But unfortunately , This level of testing is not yet available , It's mainly due to lack of time and a lot of manual coding and maintenance .Parasoft Jtest Unit test assistant not only provides unit test automation , It also provides guided test creation and dependency management , To speed up test creation and reduce maintenance .

To learn more , Read how the unit test assistant uses the simulation framework to help with dependency management 1.21.

版权声明
本文为[SWTOR]所创,转载请带上原文链接,感谢
https://javamana.com/2021/01/20210121160259188t.html

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云