• 使用PowerMockito.whennew的时候,注解preparefortest里面的类需要是mock的new代码所在的类的对象


    Mock方法内部new出来的对象

           测试目标代码:

    01

    public class ClassUnderTest {

    02

    03

        public boolean callInternalInstance(String path) { 

    04

    05

            File file = new File(path); 

    06

    07

            return file.exists(); 

    08

    09

        } 

    10

    }

           测试用例代码:    

    01

    @RunWith(PowerMockRunner.class) 

    02

    public class TestClassUnderTest {

    03

    04

        @Test 

    05

        @PrepareForTest(ClassUnderTest.class) 

    06

        public void testCallInternalInstance() throws Exception { 

    07

    08

            File file = PowerMockito.mock(File.class); 

    09

    10

            ClassUnderTest underTest = new ClassUnderTest(); 

    11

    12

            PowerMockito.whenNew(File.class).withArguments("bbb").thenReturn(file); 

    13

             

    14

            PowerMockito.when(file.exists()).thenReturn(true); 

    15

    16

            Assert.assertTrue(underTest.callInternalInstance("bbb")); 

    17

        } 

    18

    }

          说明:当使用PowerMockito.whenNew方法时,必须加注解@PrepareForTest和@RunWith。注解@PrepareForTest里写的类是需要mock的new对象代码所在的类。

    Mock方法内部new出来的对象

           测试目标代码:

    01 public class ClassUnderTest {
    02  
    03     public boolean callInternalInstance(String path) { 
    04  
    05         File file = new File(path); 
    06  
    07         return file.exists(); 
    08  
    09     
    10 }

           测试用例代码:    

    01 @RunWith(PowerMockRunner.class
    02 public class TestClassUnderTest {
    03  
    04     @Test 
    05     @PrepareForTest(ClassUnderTest.class
    06     public void testCallInternalInstance() throws Exception { 
    07  
    08         File file = PowerMockito.mock(File.class); 
    09  
    10         ClassUnderTest underTest = new ClassUnderTest(); 
    11  
    12         PowerMockito.whenNew(File.class).withArguments("bbb").thenReturn(file); 
    13          
    14         PowerMockito.when(file.exists()).thenReturn(true); 
    15  
    16         Assert.assertTrue(underTest.callInternalInstance("bbb")); 
    17     
    18 }

          说明:当使用PowerMockito.whenNew方法时,必须加注解@PrepareForTest和@RunWith。注解@PrepareForTest里写的类是需要mock的new对象代码所在的类。

  • 相关阅读:
    路由追踪BestTrace命令详解
    python MD5 信息摘要
    BFD 协议介绍
    IPSec 详细分析 二
    什么是分光器
    聊聊编码与解码(弄懂bytes,utf8,ascii,unicode)
    OS实践1: Windows 11 配置 WSL
    Mac上录屏录音
    同步相关 及音量
    iOS相关文档
  • 原文地址:https://www.cnblogs.com/nizuimeiabc1/p/12153148.html
Copyright © 2020-2023  润新知