Test用例撰写总结

    1. @RunWith:这个是指定使用的单元测试执行类,后面只可以跟一个类,常见的有下面几个

    单元测试就使用了Spring实现的执行类
    @RunWith(SpringJUnit4ClassRunner.class)
    测试单元使用了powermock的情况,后面一句实际也表示需要Spring
    @RunWith(PowerMockRunner.class)
    @PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)

    @RunWith(Parameterized.class)
    这个是干嘛的?


    1. @ContextConfiguration:使用注释的方式注入配置文件。

    单个文件
    @ContextConfiguration(Locations=”../applicationContext.xml”)

    @ContextConfiguration(classes = SimpleConfiguration.class)


    多个文件时,可用{}

    @ContextConfiguration(locations = { “classpath:/spring1.xml”, “classpath:/spring2.xml” })


    1. @PowerMockIgnore:只有在powerMock的时候才需要使用,powermock的原理是使用自定义的load来修改mock的类,所以会出现两个load的情况,具体的我也不清楚,编不下去了。

    根据编译情况自己删减
    @PowerMockIgnore({“javax.xml.“, “org.xml.sax.“, “com.sun.xml.“, “com.sun.org.apache.xerces.“, “org.w3c.dom.“,
    “javax.management.
    “, “sun.security.“, “javax.net.“})


    1. @PrepareForTest: 只有在powermock的时候需要写。主要是需要powermock的类需要写出来。

    @PrepareForTest({mock1.class, mock2.class})


    1. @DirtiesContext:加了此注解,可以保证创建新的上下文,但是会牺牲部分的性能

    @DirtiesContext
    public class CertManagementTest {


    1. @Autowired: 是使用Spring自动注入的,但是注入的不一定是实际类,最好看下xml的配置,确认他是实际类还是配置为了mock的类。

      @Autowired
      private Orchestrator orchestrator;

      在xml中如下,则表示是个mock的类



    1. @Before&@After: 是每个test方法跑之前都会跑的,before中一般包含有所有test都需要准备的东西,After中为各个类的需要回收的情况。还有@BeforeClass和@AfterClass是在类前类后被执行的

      @Before
      public void setup()
      @After
      public void tearDown()


    1. @Acc :是CT需要使用到,主要为了关联AC文件,无实际作用。

      @Acc(name = “LTE3435-T-o.5.1”, description = “Should report alarm 8515 and ignore certificate validity check when system time is not available”)


    1. @Test:每个测试类前都需要写,表示这是一个可执行的测试方法。

    @Test
    public void should_reportAlarm8515_when_ntpIsUnsynced()


    1. // given // when // then:每个测试的3个步骤,given表示准备,when表示实际执行,then表示需要校验的情况。注意注释需要空格。

    // given
    // when
    // then


    1. 常见的校验方式

    assert常见的有下面6种,这6种前面都可选打一个String,如果需要使用其他的可以参照/org/junit/Assert.class
    assertEquals:前后相等,A=B
    assertEquals(A,B);

    assertNotEquals:前后不相等,A!=B
    assertNotEquals(A,B);

    assertTrue:入参为真if(!A)fail
    assertTrue(A);

    assertFalse:入参为假if(A)fail
    assertFalse(A);

    assertNotNull:入参非空,if(A==null)fail
    assertNotNull(A);

    assertNull:入参为空,if(A!=null)fail
    assertNull(A);


    verify也是个较为常用的校验,需要注意的是verify的只能是mock的类
    verify(mockclass,times(次数可选)).方法(入参)
    他可以校验这个方法是否调到,以及检测次数
    如果是检测次数,那就是times来控制
    如果检测入参,这边需要使用到ArgumentCaptor
    ArgumentCaptor captor = ArgumentCaptor.forClass(StatusReport.class);
    verify(securityCallback).reportOperationStatus(captor.capture());
    StatusReport statusReport = captor.getValue();
    assertTrue(statusReport.getContent().contains(expectedNotification));


    1. 常见的预设条件的方法

    when(mock.isOk()).thenReturn();
    when后面跟mock类的方法,return中返回这个方法本身需要返回的类。
    when(ne3sServiceSwitch.isNe3sRejectNewRequest(any())).thenReturn(true);

    doReturn().when(mock).method();
    这个和上面的区别,主要体现在spy的情况下,spy的时候会出现真实的类,这个时候thenReturn会实际执行,而doReturn会直接返回。对于MOCK实际两个来说没啥区别

    thenThrow:需要丢出exception的时候使用
    thenAnswer:你在这个函数被调用到的时候,你需要做一些额外的动作时使用,他可以满足你的好多幻想,比如你可以写分支,不同情况返回不一样的。或者是不是可以又return又throw的,没试过。

    thenCallRealMethod:当被调用时,会调用实际方法。这个我感觉不是很好用,风险比较大,少用吧。

    对于do也实际有这些方法
    下面是一个关于定时器的做法,主要是当有两个线程的时候,等待使用。
    //新建一个定时器,入参表示几次才能解除
    final CountDownLatch latch = new CountDownLatch(1);
    //在调用到某个方法时解除定时器
    doAnswer(releaseLatch(latch)).when();
    //实际定时器等待,入参为定时器时间
    latch.await(2, TimeUnit.SECONDS);
    //解除的方法
    private Answer releaseLatch(CountDownLatch latch) {
    return invocation -> {
    latch.countDown();
    return null;
    };
    }
    Whitebox是一个常见的访问和修改私有变量的方法,final没法搞
    设置私有变量
    @Autowired
    private Keys key;
    //修改key这个类里面的keyPair变量名的变量为keyPairMock
    Whitebox.setInternalState(key, “keyPair”, keyPairMock);

    访问私有变量
    //访问获取securityHandler中的operationInfoManager变量
    operationInfoManager = (OperationInfoManager) Whitebox.getInternalState(securityHandler,
    “operationInfoManager”);

    需要访问私有方法的时候就需要反射的方法
    //LocalAgentImpl的类中的filterSensitiveInfoSyncToHcache名字的方法,他的入参是InfomodelUpdate.class类型,我的理解他给了入参的类型主要是为了同名不同入参的方法做的一个区分。
    Method method = LocalAgentImpl.class.getDeclaredMethod(“filterSensitiveInfoSyncToHcache”, InfomodelUpdate.class);
    //将私有的方法访问设置为true则可以访问了。
    method.setAccessible(true);
    //实际调用这个方法,使用invoke,第一个入参表示实际的类,后面的是入参。
    InfomodelUpdate updatedEvent = (InfomodelUpdate) method.invoke(localAgent, event);


    1. mock spy

    mock是最常见的模拟手段,写法也比较简单。
    ClassC a = mock(ClassC.class);
    mock之后你可以控制调用后的返回信息。
    也可以进行校验。
    mock之后这个类实际完全没有了
    所以当调用到mock的这个类的方法
    而你有没有给它指定when的动作,就会出现空指针的情况
    ClassC a = spy(new ClassC);
    spy是有真实类的,我们可以改变其中几个方法的返回情况
    而对于spy来说我们要谨慎的时候用when().then这样的语句。
    不知道对于spy来说when().thenCallRealMethod会怎么样(也许会调两遍?)


    1. powermock: 实际过程当中需要尽量少的使用,至于少用的原因我也不知道,但是它很好用,千万不要尝试去搜索它,因为你会爱上它

    Mock方法内部new出来的对象
    ClassC a = PowerMockito.mock(ClassC.class);
    PowerMockito.whenNew(ClassC.class).withArguments(“xxx”).thenReturn(a);
    需要注意whennew的对象需要放到PrepareForTest

    Mock static的量:
    ClassC a = PowerMockito.mockStatic(ClassC.class);
    对于代码中执行了shell脚本的情况,就是需要使用到mockStatic,可参考如下
    mockStatic(ShellScriptExecutor.class);
    when(ShellScriptExecutor.execute(anyBoolean(), anyObject(), anyObject(), anyObject()))
    .thenReturn(new ShellScriptResult(true, “”, “”, 0));


    1. Matchers的使用

    any系列,any就是whocare,写不出的时候就用它
    any();我感觉他和anyObject一样的
    anyBoolean();
    anyByte();
    anyObject();
    anyString();

    eq系列,就是要相等这个
    这里有一些很秀的方法,有兴趣可以研究下
    isA
    refEq
    same
    That系列
    最常用的就是argThat,主要是要控制入参,前面说到的ArgumentCaptor是用来检测
    这边要注意的是使用That系列,你需要自己去实现一个Matcher
    doAnswer(latcher).when(changeListenerMock).onChange(argThat(new CmpMatcher(nack)));
    class CmpMatcher extends ArgumentMatcher {
    private String distName;
    public CmpMatcher(String distName) {
    this.distName = distName;
    }

    @Override
    public boolean matches(Object argument) {
    InfomodelUpdate data = (InfomodelUpdate)argument;
    return distName.equals(data.updated.entrySet().stream().findFirst().get().getKey().asString());
    }
    }