Junit单元测试

xiaoxiao2021-02-28  63

1.导包

<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency>

2.一般测试 定义测试类,在测试方法加入@Test注解。

public class TestData { @Test public void testValueSet() throws Exception { //测试代码 } }

如果引入了spring-boot-starter-test这个包,判定测试结果会比较容易,因为这个包内有hamcrest-core-1.3.jar、hamcrest-library-1.3.jar封装了很多断言种类。直接静态引入就可以使用。

import static org.junit.Assert.*; import static org.hamcrest.Matchers.*; >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> assertThat(T actual, Matcher<? super T> matcher); assertTrue(boolean condition); .... ...

@BeforeClass 在测试方法、测试类之前运行,@AfterClass是在之后运行,只运行一次。绑定方法只能是以public static void开头。而@After和@Before是在每个方法运行前都会执行。

3.maven如何给单元测试传参数 mvn clean install -Dname=XXX Java通过System.getProperty(“name”);即可取到。

4.单元测试调用私有方法、操作成员变量等(反射机制)

Class service = MyClass.class; Field field = service.getDeclaredField("Field Name"); field.setAccessible(true);//访问私有方法或变量的关键 field.set(instance, new);//在实例instance内改变字段的值 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Method targetMethod = service.getDeclaredMethod("Method Name", String.class, ValidatorModel.class);//方法名、参数类型... targetMethod.setAccessible(true);
转载请注明原文地址: https://www.6miu.com/read-53401.html

最新回复(0)