Developer Prerequisites: Unit Test _ Software test

Source: Internet
Author: User
Tags assert testng
 Talking about the software test four words, I think we have come up with integrated testing, system testing, black box testing, white box testing, probably just did not expect to have unit test. For the university is a software engineering students from the background may have heard these four words, to work for several years old veteran may have heard but not actually used in the majority. The vast majority of developers are busy developing the work at hand, and will not take unit test into the scope of work, they will say, I am not even busy with functional development, which have time to do unit testing, and also to write test code, it is not a repeat of the code to write a function.     But is it really not worth the time to do unit testing because you may not know how much input/output ratio of unit tests is, and here's a quick introduction to how much the unit test can do for developers. What is unit testing and why do unit tests do not write unit tests excuse the mainstream framework JUnit and TestNG Android Unit Test Summary What is unit Test unit testing is essentially code, unlike normal code It is code that validates the correctness of the code.    A simple definition can be made: unit tests are code written by developers to detect the correctness of the target code under specific conditions. Software development is inherently complex, no one dares to say that they write the code is not a problem, or not tested to ensure the correct operation of the code, you may be in this execution path can be executed, but there are other paths, there are one by one to verify it, so,   In order to ensure the correctness of the program, we must strictly test our code.   As a simple example: There is a calculation class, which has an Add method, the operation is two numbers to add. public class Calculator {   public int add (int one, int another) {       //is just a simple two-phase    Plus        return one + another;   &NBSP} General Practice: If you write this method, you want to verify the correctness of the Add method, you need to write a main function using the Add method, first instantiate the Calculator class, then call the Add method and pass in two parameters, such as 1 and 2. Then you run the project, see if the result is 3, if it is 3, it means that I write this method without errors, may not be tested, continue to develop follow-up functions, if not 3, then go back to see where the code went wrong, debugging, and even sometimes the naked eye can not see what the code error, at this point to introduce breakpoints to see, during this period, a large part of the time spent on breakpoints, debugging, running. Unit Test Practice: First, use the JUnit test framework (as described later in this framework) to write a test code, as follows: public class Calculatortest {   public void Testadd () throw    s Exception {       calculator Calculator = new Calculator ();           int sum = Calculator.add (1, 2);           assert.assertequals (3, sum);   &NBSP}} Here the Calculatortest is the Calculator corresponding test class, where testadd corresponding to the test method of add, testing is generally divided into three steps: Setup.   It is generally new to the class you want to test, for example: Calculator Calculator = new Calculator (); Perform the action.   It's generally called the method you want to test to get the results of the run: int sum = Calculator.add (1, 2); Verify the results.   Verify that the results are the same as expected: Assert.assertequals (3, sum);   See assert this keyword, here can be understood as assertions or expectations, according to the value of the input, expect to have a value output, rather than by the naked eye to verify that is not the value of their own, is directly judged by the equality of the value is more objective to verify.    The above is just a little bit of unit testing, so what more can it bring us. Why do unit tests usually we do any work to consider its return first, and write code more so. If the unit test doesn't work very well, no one will be willing to write a bunch of useless code, so what is the advantage of unit testing? As follows: facilitate later reconstruction. Unit tests can provide protection for the refactoring of your code, and as long as the unit tests run through after refactoring the code, it is largely said that this refactoring did not introduce new bugs, and of course thisis built on the basis of complete and effective unit test coverage. Optimized design.   Writing unit tests will allow users to view and think from the caller's perspective, especially with the development approach of TDD-driven development, allowing the user to design the program as easy to invoke and testable, and to release coupling in the software. Document Records.   A unit test is a priceless document that is the best document to show how a function or class works, a document that compiles, runs, and keeps up to date, always synchronizing with code. has a regressive nature.   Automated unit testing avoids code regression, and when written, you can quickly run tests anytime, anywhere, rather than deploying the code to a device and then manually overwriting a variety of execution paths, which is inefficient and time-consuming.   And so on, so many advantages, nothing more than good interface design, correctness, regression, testable, perfect call documents, high cohesion, low coupling, these advantages are enough to let us focus on unit testing, but personally feel that there are more important reasons. First, bring confidence. When taking on a new project, or participating in a new project development, it is often that you participate halfway through, you need to interpret and understand the existing code structure, for business understanding, the code of the various modules in the understanding of the relationship. If you start with a financial error, it is likely that the modified code will cause more bugs appear, and then need to fix more bugs, changed a place, it is likely to inexplicably affect another place, this phenomenon is very common. There is also a situation, assuming that you modify the function is no problem, but need to test the verification, in the test when you need to consider the function point of its original test path, and need one by one to verify the functional path, to prove that this modification for the existing function point does not affect. There is a lot of time cost, resulting in inefficient. Whether there is such a way, I need to modify the place I want to change, do not need to care about the impact of the changes after the change, and do not need to care about its test regression, there, this is the time unit Test debut.   Write unit test code, can let me write the code enough self-confidence, it is able to withstand the test. Second, faster feedback. For a developer with some programming experience, when he gets a new requirement, the first thing to think about is not to do coding, but to think about the structure of the code, some classes, how the data structure should be, and then start knocking the code. If there is no unit test, the general process is basically the function of the module is completed before starting to test, such as the use of the MVP architecture. Generally start model module, and then improve the presenter module, the last write View module, and so on these several modules have been written, and then run the APP, verify that they write the function of the module to meet the needs, no compliance is to continue to go back to modify the code, whichIt takes a long time to know if the code you are writing is right for you to meet the requirements. Is there a way of instant feedback, there, write unit test can be, when you write a function, immediately match a unit test function, so that the way to write that can ensure that the code you write on the spot immediately to modify, test through a, it means to complete a small function point, and finally, the function assembled,   Is that we want a big functional point. Finally, save time. For Android Development, running the app over and over again, and then performing the appropriate user action to see if the interface is displaying correctly, testing the functionality in this way is a waste of time and inefficiency, and unit testing can be performed with little open APP. Of course some need some resources file is the need for APP operating conditions, most of the function in the unit testing phase can be verified, then the speed is much faster.    In addition, unit tests can help reduce bugs, reducing the time to debug bugs, and some low-level mistakes can be avoided during unit testing. Do not write unit test excuses many developers do not write unit tests, the most important reason is that they do not know what the unit test can bring benefits, or even do not understand the word unit test, which naturally like parallel lines with no intersection. Another important reason is that some developers ' programming ideas are still at a relatively early stage, the development software just realizes the function, what high cohesion, the low coupling, the reconstruction, the design, the test and so on thought is too specialized, to these terms and the meaning does not understand, this naturally will not consider uses. There are also some non ideological reasons, as follows: unit tests take too long. The software development work is so busy that the code has no time to write unit tests. This may be the most common excuse for developers, and in some ways that's not an excuse, because many developers do spend a lot of time at work. But is this really the case, have you ever thought that the cause of overtime may be that you spend too much time on manual tests, debugger: You may not be thinking about flexibility and design so that you need to spend a lot of time in a complex code heap to perform certain functions when the requirements change, and these changes may introduce new bugs.   It will also lead to time-consuming manual testing, debugging, and so on, and so on, the code will become more and more messy, more and more difficult to maintain, and ultimately lead to endless overtime. It's not my job to test. Testing is not really a developer's job, but unit testing is really a developer's job, there are many kinds of tests, and only unit tests are a developer's job category. Developers to write code for the application, then naturally need to ensure the correctness of the code, and unit testing is this guarantee of the correctness of the Code white Box test, that is, understanding the internal structure of the code of the logic of the case for purposeful testing, since when it comes to understanding the code,Then the developer is naturally the most authoritative person.   Therefore, it is the responsibility of the developer to write unit tests and to submit the correct code to the tester for additional testing. The code has been compiled and measured. Generally speaking, this is an excuse that will not be put on the mouth but may be hidden in the heart.   Code compilation can only say that the code you write conforms to the grammatical requirements, and does not represent a guarantee of correctness. The code originally had no unit tests and was difficult to test. This problem is basically to accept and maintain the code developed by others, and the original code itself has no unit test, and then add if the code coupling is high, it is more difficult to write unit tests for these code.   At this point, when you understand the code, you first add unit tests to the parts that you can test, ensure that these testable parts are not contaminated, then refactor the code after you have a good understanding of the code, reduce the coupling of the code, and slowly supplement the test cases to build up the coupling and testability of the code. Mainstream frameworks JUnit and TestNG JUnit are a unit test framework for the Java language, an example of the XUnit Unit Test architecture system, for writing and running repeatable tests. It includes the following features: Assertions used to test the expected results (assertion) a test tool for sharing common test data for easy organization and run test suite graphics and text test-run TestNG is a test framework inspired by JUnit and N Unit, but introduces some new features that make it more powerful and easier to use. TestNG eliminates most of the old framework constraints, enabling developers to write more flexible and powerful tests.   Because it draws heavily on Java annotations (JDK5.0 introduced) to define tests, it can also show how to use this new feature in real-world Java-language production environments. Features are as follows: annotation TestNG use Java and object-oriented features to support comprehensive class testing (for example, by default, without creating a new instance of a class that tests each test method) independent compile-time test code and RUN-TIME Configuration/Data information Flexible run-time configuration The main introduction is "test Group". When compiling the test, just ask TestNG to run all the "front-end" tests, or "fast", "slow", "database", etc. support dependent test methods, parallel test, load test, local fault flexible plug-in API support multithreaded Test unit test in Android because The JUnit test framework is based on the Java language, and of course Android development is also based on the Java language, so in Android weYou can use the JUNIT4 Unit test framework for regression testing, but at the same time, Google also provides a ANDROIDJUNIT4 test framework, looking at the name to know that it is based on the JUnit 4 framework for unit testing in the Android environment. So, what's the difference between ANDROIDJUNIT4 and JUNIT4? A big difference is that the 1,ANDROIDJUNIT4 test can be done in a real machine environment.   For example, you have to test the file to read the SD card, or operate the Sqllite database, these conditions only in the real machine, at this time you use the ANDROIDJUNIT4 frame test, you can run directly with the real environment to do the corresponding unit test. 2,JUNIT4 test is run in the project, that is, in the compile phase.   If you want to simulate the Android environment at this point, for example, I want to test the activity class with JUNIT4, then I need to refer to the Third-party library to support, reference the Mockito and robolectric framework to simulate the Android environment for the corresponding unit tests.    So when you use ANDROIDJUNIT4 and JUNIT4 different frameworks for unit testing, see what you're going to test for, and then make a different choice. Summary overall, unit testing is not an integration test, unit testing is simply testing a method unit, not testing an entire process. Integration testing is a system test of end to end. Test related modules integrated in accordance with the expected work, is generally interface or functional level of testing, may rely on a number of system factors, the test code logic is generally more complex, the running time will be longer, the repair costs after the error is high. The unit test is that the developer has done a self-test before the integration test, and, after unit testing, one by one validation of a method's execution path combination, focusing on only three goals: a definite return value.   For example, a function is unit tested to verify that its return value conforms to the expected result.   This function only changes some properties or states within its object, and the function itself does not return a value to verify the property and state it has changed. Some functions do not return a value, and do not directly change the state of which value, which requires validation of its behavior, such as click events.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.