当前位置:网站首页>Unit test based on junit4
Unit test based on junit4
2022-06-10 11:19:00 【andQVQ】
List of articles
Basic idea of test class
- mock Introducing test classes in .
- Initialize the objects and reference classes in the class , Establish a mapping relationship .
- Build the data and requests that need to be tested , Test the function for correct operation .
Test sequence
@Test: This note shows that it is attached to JUnit Of public void Method can be used as a test case .
@Before: Some tests need to create several similar objects before they run . stay public void Method is annotated because the method needs to be annotated in test Method .
@After: If you put external resources in Before Method , So you need to release them after the test runs . stay public void Method is annotated because the method needs to be annotated in test Method .
@BeforeClass: stay public void Method is annotated because it needs to run before all methods in the class .
@AfterClass: It will make the method execute after all the tests are finished . This can be used for clean-up activities .
@Ignore: This comment is used to ignore tests that don't need to be executed .
stay before() Methods and after() Between methods , Execute every test case .
@RunWith(SpringRunner.class)
Test class initialization . Mark... At the beginning of the test class , Indicates the operating environment , For example, start and create spring Application context . Otherwise, you need to write a bunch of environment configuration code at startup .
@Mock:
In unit test , We often want to test a method in a class independently , But this class is not independent , It will call some methods of other classes and service, This leads to the following two problems :
- External services may not work properly in the context of unit testing , Because they may need to access the database or call other Http service .
- Our test focuses on the implementation of this class , Some behaviors of external classes may affect our testing of this class , That will lose the significance of our single test .
stay Mockito Is used to create mock object , How to use it is as follows :
@Mock
private ClassName mockedObject;
The above code creates a file named mockedObject, The type is ClassName Of mock object , All methods of this object are set to null , Use... As needed to test code logic
MockitoAnnotations.initMocks(this);
Give Way @Nock Annotations to take effect
Mock The default value of method
Mock When the method of the object does not have a test stake set ,Mockito Will return the default value of the method return type , No mistake. .mock By default, the instance will add basic implementations to all methods : return null Or empty set , perhaps 0 And other basic types . It depends on the method return type
List mockList = mock(List.class);
when(mockList.get(5)).thenReturn("hello");// Pile driving
Assert.assertEquals("hello", mockList.get(5));// The pile driving scenario returns to the set value
Assert.assertEquals(null, mockList.get(10));// There will be no error in the case of not piling , Return default
Parameter matcher (matchers)
Belong to Status test
Are static methods , To put it bluntly mock Some conditions of the method
List several typical matchers :
any() : Any parameter
any(OrderInfo.class): whatever OrderInfo( Custom classes in development )
anyString() : Any string , Equate to any(String.class)
eq(1): Specific value 1
InvokeService Class , To be mock Methods
public Integer targetMethod01(String param01, Integer param02) {
return 1;
}
Test class TargetClassTest in :
@Mock
private InvokeService mockService;
@Test
public void dmeoTest() {
Mockito.when(mockService.targetMethod01(any(), any())).thenReturn(666);
Mockito.when(mockService.targetMethod01(any(String.class), anyInt())).thenReturn(666);
Mockito.when(mockService.targetMethod01("demo", 1)).thenReturn(666);
Mockito.when(mockService.targetMethod01(eq("demo"), eq(1))).thenReturn(666);
// It's all right , Here's how it's written , An error will be reported during the execution of the single test
Mockito.when(mockService.targetMethod01(eq("demo"), 1)).thenReturn(666);
}
Once the parameter matcher is used to verify , Then all parameters should use parameter matching
Behavioral tests
Some of the time , The test doesn't care about the returned results , It focuses on whether the method has been called by the correct parameters . conceptually , It is different from state testing “ Behavioral tests ” 了 .
Once the use mock() or @Mock Generate mock objects , signify Mockito It will record what methods are called by the mock object , And how many times 、 Sequence of calls, etc . Finally, it is up to the user to decide whether authentication is required .
times(x):mock Method is called x Time
never(): Never called , Equivalent to times(0)
atLeast(x): At least called x Time
atLeastOnce(): At least called 1 Time , Equivalent to atLeast(1)
atMost(x): At most x Time
verify(): All method calls and parameter calls are tracked internally , Then it will return a result , State whether it passes . It can also be like when Use a parameter matcher like that .
field
Determine whether the class contains a field
RefelctionUtils.findFiled(class, name);
send filed Become accessible
ReflectionUtils.makeAccessible(field);
Set object property values directly
ReflectionUtils.setFiled(Field field, Object target, Object value);
Assert
assert It means to assert , This keyword can determine whether the result of the Boolean value is the same as expected , If it is the same, it will be executed normally , Otherwise it will throw AssertionError.
void assertEquals(boolean expected, boolean actual): Check whether two variables or equations are balanced
void assertTrue(boolean expected, boolean actual): The check condition is true
void assertFalse(boolean condition): The check condition is false
void assertNotNull(Object object): Check object is not empty
void assertNull(Object object): Check object is empty
void assertSame(boolean condition):assertSame() Method to check whether two related objects point to the same object
void assertNotSame(boolean condition):assertNotSame() Method to check whether two related objects do not point to the same object
void assertArrayEquals(expectedArray, resultArray):assertArrayEquals() Method to check whether two arrays are equal
JUnit Time test
If a test case takes more time than a specified number of milliseconds , that Junit It will be automatically marked as failed .timeout Parameters and @Test Use notes together . Is it powerful ?
@Test(timeout=1000)
JUnit Parametric testing
Junit 4 A new functional parametric test is introduced . Parametric testing allows developers to run the same test over and over again with different values . You will follow 5 There are three steps to create a parametric test .
- use @RunWith(Parameterized.class) To comment test class .
- Create a by @Parameters Public static methods of annotations , It returns a collection of objects ( Array ) As a set of test data .
- Create a public constructor , It takes the same thing as a line of test data .
- Create an instance variable for each column of test data .
- Use instance variables as a source of test data to create your test cases .
Once each row of data appears, the test case will be called .
Reference resources 1
Reference resources 2
Reference resources 3
Reference resources 4
边栏推荐
猜你喜欢

87. (leaflet house) leaflet military plotting - straight arrow modification

中台:数据中台、业务中台、技术中台、应用中台、AI中台……
![[signalr complete series] Implementation of signalr packet communication in net6](/img/d8/a367c26b51d9dbaf53bf4fe2a13917.png)
[signalr complete series] Implementation of signalr packet communication in net6

【万人独木桥】那个夏天—后高考生活该如何安排?

Meetup回顾|DevOps&MLOps如何在企业中解决机器学习困境?

kubernetes常用命令-1-命令补全

Practice of Flink CDC in Dajian cloud warehouse

图文,文字预训练方式长期学习ing。

API如何检测安全配置是否有错误?

Gan learning notes KL divergence, JS divergence, Wasserstein distance
随机推荐
常用颜色RGB、灰度值、取色值、透明度。
[PaperNote] Web3 Direction
PV operation daily question - ticket sales
Detailed explanation of redis
如何才能把团队给带解散。。。
爱可可AI前沿推介(6.10)
LVS+Keepalived高可用群集
Flink CDC + Hudi 海量数据入湖在顺丰的实践
cocoslua在vs2013的调试方法
使用matlab生成正弦波、三角波、方波的COE文件
Carbon reduction in the construction industry is by no means a fresh idea experts suggest strengthening the transformation of rural buildings
你的下一台电脑何必是电脑,探索不一样的远程操作
牛客面经02
NoClassDefFoundError 和 ClassNotFoundException 有什么区别
C#大作业——学生信息管理系统
string类及学习使用文档
On line monitoring of oil content in compressed air of power plant with PID photo ionization detector
87. (leaflet house) leaflet military plotting - straight arrow modification
关于单向链表
More durable game real wireless headset with large battery and long endurance. Hero G1 can use it