Unit testing with PowerMock

Unit testing can improve the efficiency of test development, reduce code error rate, improve code robustness and improve code quality. There are two commonly used testing frameworks in Spring framework: PowerMockRunner and SpringRunner. In view of a series of dependency and data connection problems started by SpringRunner, PowerMockRunner is recommended, which can effectively improve the efficiency of testing. Moreover, its API can cover a wide range of scenarios and is easy to use. It can be described as a sharp simulation tool for Java unit testing.

1. What is powermock?

PowerMock is a Java simulation framework that can be used to solve test problems that are usually considered difficult or even impossible to test. Using PowerMock, you can simulate static methods, delete static initializers, allow simulation without relying on injection, and so on. PowerMock accomplishes these tricks by modifying bytecode at run time while executing tests. PowerMock also includes utilities that make it easier for you to access the internal state of objects.

For example, when you use Junit for unit testing, you don't want the test data to enter the database. What should you do? At this time, you can use PowerMock to intercept database operations and simulate the return parameters.

2. PowerMock package introduction

<!-- Unit test dependency-->
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-core</artifactId>
            <version>2.0.2</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <version>2.23.0</version>
        </dependency>
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-module-junit4</artifactId>
            <version>2.0.4</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-api-mockito2</artifactId>
            <version>2.0.2</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.github.jsonzou</groupId>
            <artifactId>jmockdata</artifactId>
            <version>4.3.0</version>
        </dependency>
        <!-- Unit test dependency-->

3. Important notes

@RunWith(PowerMockRunner.class) // Tell JUnit to test with PowerMockRunner
@PrepareForTest({RandomUtil.class}) // All classes to be tested are listed here, which is applicable to the simulation of final classes or classes with final, private, static and native methods
@PowerMockIgnore("javax.management.*") //To solve the problem of classloader error after powermock is used

4. Use examples

4.1 analog interface return

First mock the interface, and then record the relevant behavior

InterfaceToMock mock = Powermockito.mock(InterfaceToMock.class)

Powermockito.when(mock.method(Params...)).thenReturn(value)

Powermockito.when(mock.method(Params..)).thenThrow(Exception)
4.2 setting the private attribute of an object

You need to use whitebox to assign values to class es or objects.

If we have done our best to mock the interface, now we need to add this mock to the object. You can use the following methods:

Whitebox.setInternalState(Object object, String fieldname, Object... value);

Where object is the static class or object whose properties need to be set.

4.3 simulation constructor

For the simulation constructor, that is, when new InstanceClass() appears, this constructor can be intercepted and replaced with the mock object we need.

Note: you need to add a mark when using:

@RunWith(PowerMockRunner.class)

@PrepareForTest({ InstanceClass.class })

@PowerMockIgnore("javax.management.\*")

Powermockito.whenNew(InstanceClass.class).thenReturn(Object value)
4.4 simulation static method

Simulating a static method is similar to simulating a constructor, and you also need to add annotation tags.

@RunWith(PowerMockRunner.class)

@PrepareForTest({ StaticClassToMock.class })

@PowerMockIgnore("javax.management.\*")

Powermockito.mockStatic(StaticClassToMock.class);

Powermockito.when(StaticClassToMock.method(Object.. params)).thenReturn(Object value)
4.5 simulation final method

The simulation of the Final method is similar to the simulation of the static method.

@RunWith(PowerMockRunner.class)

@PrepareForTest({ FinalClassToMock.class })

@PowerMockIgnore("javax.management.\*")

Powermockito.mockStatic(FinalClassToMock.class);

Powermockito.when(StaticClassToMock.method(Object.. params)).thenReturn(Object value)
4.6 analog static class

Simulating static classes is similar to simulating static methods.

4.7 using spy method to avoid executing member functions in the tested class

If the tested class is TargetClass, the method to be masked is targetMethod

1) PowerMockito.spy(TargetClass.class);

2) Powemockito.when(TargetClass.targetMethod()).doReturn()

3) Attention to join

@RunWith(PowerMockRunner.class)

@PrepareForTest(DisplayMoRelationBuilder.class)

@PowerMockIgnore("javax.management.*")
4.8 parameter matcher

Sometimes we don't want to make exact matching when processing doMethod(Param param). At this time, we can use the fuzzy matching method provided by Mockito.

E.g. mockito anyInt(),Mockito.anyString()

4.9 static methods for handling public void type
Powermockito.doNothing.when(T class2mock, String method, <T>... params>

5. Optional list of unit test cases

  • 5.1 input data verification: This section contains a series of checks that can usually be applied to data entered into the application system.
    • Required item test
    • Unique field value test
    • Null value test
    • Field accepts only allowed characters
    • Negative value test
    • Field length specification
    • Impossible value
    • Garbage value test
    • Check dependencies between fields
    • Equivalent class division and boundary condition test
    • Error and exception handling test

    5.2 date verification: This constitutes a set of conditions for the date field.

    • Various date formats
    • American style date format
    • Effective date
    • Invalid date, for example
    • Months 00 and 13
    • Day does not contain 00 and 32 as its values
    • 28, 29 and 30 have been verified correctly
    • Check the impact of weekends and bank holidays
    • Link between February 29, 2008

    5.3 time verification: This constitutes a set of conditions for the time field

    • Various time formats, such as 12 / 24-hour format, AM / PM
    • Check effective time
    • Check invalid time
    • Check the impact of weekends and work holidays

    5.4 postal code verification: This constitutes a set of conditions for the zip code field

    • Test partial zip code entry and check zip code format
    • Test space / no space
    • Check if there is an option to enter the address manually

    5.5 system interface: This constitutes a set of conditions for fields transferred between multiple application systems.

    • Check whether all fields / parameters on the interface are executed correctly
    • All data fields need to work according to the validation list
    • Security testing across automated interfaces
    • Check inheritance

    5.6 availability: This constitutes a set of conditions that help verify the availability of the application system.

    • Check whether the layout is consistent with the design standards
    • Check font, color, size, etc.
    • Test brand guidelines
    • Check whether the window title of each application has the name of the application and the name of the window
    • Check alignment
    • Check that the screen can be resized and minimized
    • Spell check
    • Test the default values if necessary
    • Required fields need to be highlighted with an asterisk

    5.7 safety: This constitutes a set of conditions to help verify the security of the application system.

    • Password not visible
    • Access test - multiple levels
    • Change password
    • Error messages should not reveal any system information
    • Check that SSL is deployed correctly
    • Check whether locking rules are applied
    • Check whether the password is saved in clear code or encryption
    • Validate the application with a valid UserId and an invalid UserId
    • Validate the application with valid passwords and various invalid passwords
    • Check access to the application by entering a valid URL directly. The system should ask for login details.
    • Make sure the browser doesn't remember the password

    5.8 record, review and tracking: This consists of a set of conditions that help verify the audit records, system logs, etc. of the application system.

    • Check whether the log is saved within the specified time period
    • Check whether the log contains personal data
    • Check whether the administrator function is recorded
    • Check whether the user lock event is logged

    5.9 business application logic: This constitutes a set of conditions that help validate the application logic and business processing of the application system.

    • Check that all available product options have been explored
    • Check all upgrade and downgrade paths and options
    • Verify that the upgrade and downgrade have been applied to billing, network, self-service, etc
    • Stop / disconnect / terminate behavior
    • Equipment failure behavior
    • Check the rounding of the calculated amount
    • Ensure the full scope, type / status / condition of the test account used
    • Check that the currency symbol is displayed as required
    • Verify that there are no duplicate records.
    • Where arithmetic is involved, a large or very large number / number is used to check for overflow in the form of displayed and actual data

    5.10 report: This section contains a set of checks that help verify the reporting capabilities provided by the system.

    • All fields are available
    • The field should have enough space
    • Enable scrolling and panning
    • The page number indicates the report size (N of M) and should allow access to the middle / end points in the report
    • The report was correctly exported to an Excel / Word document
    • The report can be printed correctly and all data can be displayed correctly
    • Check that all pages in the report are accessible

    5.11 environment: This section contains a set of inspections that help verify the environmental or equipment requirements of AUT.

    • Test with all browsers
    • Test by enabling and disabling Java Script

    5.12 email: This section contains a set of checks that can be used to verify e-mail functionality

    • Verify that a confirmation message is provided when sending e-mail
    • Verify that the link provided in the e-mail message is working properly
    • Confirm that the reply address is correct
    • Verify that the font, size, and text alignment in the email are correct

    5.13 search criteria: This section contains a series of checks on the application system search function.

    • Verify that the scroll bar is implemented
    • Verify that the alignment results are correct
    • Verify that valid results are displayed for any combination of search criteria.
    • Verify that the correct results are retrieved for the AND / OR condition
    • The validation results are displayed in alphabetical or specified order
    • Verify that column headers are sortable

Added by Karamja on Fri, 07 Jan 2022 11:45:08 +0200