zoukankan      html  css  js  c++  java
  • java单元测试

    1.Junit
    @Test : 测试方法,测试程序会运行的方法,后边可以跟参数代表不同的测试,如(expected=XXException.class) 异常测试,(timeout=xxx)超时测试
    2. @Ignore : 被忽略的测试方法
    3. @Before: 每一个测试方法之前运行
    4. @After : 每一个测试方法之运行
    5. @BeforeClass: 所有测试开始之前运行
    6. @AfterClass: 所有测试结束之后运行
     
    assertTrue(String message, boolean condition) 要求condition == true
    assertFalse(String message, boolean condition) 要求condition == false
    fail(String message) 必然失败,同样要求代码不可达
    assertEquals(String message, XXX expected,XXX actual) 要求expected.equals(actual)
    assertArrayEquals(String message, XXX[] expecteds,XXX [] actuals) 要求expected.equalsArray(actual)
    assertNotNull(String message, Object object) 要求object!=null
    assertNull(String message, Object object) 要求object==null
    assertSame(String message, Object expected, Object actual) 要求expected == actual
    assertNotSame(String message, Object unexpected,Object actual) 要求expected != actual
    assertThat(String reason, T actual, Matcher matcher) 要求matcher.matches(actual) == true
     
    2.mockito:
     
    测试无参数函数mock
    String mocked = "mocked Return";
    Demo demo = Mockito.mock(Demo.class);
    Mockito.when(demo.methodNoParameters()).thenReturn(mocked);
    Assert.assertEquals(demo.methodNoParameters(), mocked);
    2、构造有基本类型作为参数的返回
    Mockito.when(demo.speak(Mockito.anyString())).thenReturn(word);
    Assert.assertEquals(demo.speak("你好"), word);
     
    3、构造有基本类型作为参数,但是只针对特定参数输入才mock返回值
    Mockito.when(demo.speak(Mockito.matches(".*大爷$"))).thenReturn(word);
    Assert.assertEquals(demo.speak("隔壁李大爷"), word);
     
    4.构造mock的函数抛出异常
    Mockito.when(demo.speak(Mockito.anyString())).thenThrow(new Exception());
     
    5.某些反复调用,我们希望对于每次调用都返回不同的mock值
    Mockito.when(demo.speak(Mockito.anyString())).thenReturn(word).thenReturn(word1);
     
    6.验证函数执行是否经过了mock
    Mockito.when(demo.speak(Mockito.anyString())).thenReturn(word);
    Assert.assertEquals(demo.speak("你猜"), word);
    Mockito.verify(demo.speak("你猜"));
    //下面这个参数的方法调用并没有被执行过,所以会抛出NotAMockException的异常
    Mockito.verify(demo.speak("nicai"));
    7.不光要对方法的返回值和调用进行验证,同时需要验证一系列交互后所传入方法的参数。
    那么我们可以用参数捕获器来捕获传入方法的参数进行验证,看它是否符合我们的要求。
    argument.capture() 捕获方法参数
    argument.getValue() 获取方法参数值,如果方法进行了多次调用,它将返回最后一个参数值
    argument.getAllValues() 方法进行多次调用后,返回多个参数值
     
    boolean updated = personDAO.update( 1, "David" );
    ArgumentCaptor<Person> personCaptor = ArgumentCaptor.forClass( Person.class );
    verify( personDAO ).update( personCaptor.capture() );
    Person updatedPerson = personCaptor.getValue();
    assertEquals( "David", updatedPerson.getPersonName() );
  • 相关阅读:
    input清楚阴影 number属性
    转 溢出隐藏
    多行,溢出隐藏 css
    JS判断移动端还是PC端(改造自腾讯网) 仅用于宣传动画,下载页等
    项目开发(Require + E.js)
    showPrompt弹框提示
    图形验证码
    CSS常用技术总结!~~
    移动开发常用技术总结!~~
    JavaScript常用技术总结!~~
  • 原文地址:https://www.cnblogs.com/wzj4858/p/8206648.html
Copyright © 2011-2022 走看看