springboot框架下的测试方法

以下为springboot项目中对public以及private方法的junit测试的方法总结:

1.单独对public方法的测试:

@Runwith(mockitoJunitRunner.class)

@springBootTest

public class xxx{

@spy

@InjectMocks

XXXXXservice  xxxservice;

@mock

测试类中的调用类

@Test
public void test1(){

//无返回值的方法
Mockito.doAnswer(new Answer<Object>() {
            public Object answer(InvocationOnMock invocation) {
                Object[] args = invocation.getArguments();
                return "called with arguments: " + args;
            }
        }).when(对象).方法名();
//有返回值
when (对象.方法 (参数)).thenReturn (方法的返回值);

      }
}

 

2.单独对private(protected方法也可)方法的测试:

@Runwith(springRunner.class)

@springBootTest

public class xxx{

@InjectMocks

XXXXXservice  xxxservice;

@mock

测试类中的调用类

@Test
public void test1(){

Sample sample = new Sample();
Method method = Sample.class.getDeclaredMethod("方法名", int.class, 引数型2...);
method.setAccessible(true);
int n = 2;
int actual = (戻り値の型)method.invoke(xxxservice,2,引数2...);

      }
}

3.对public方法中调用的private以及public方法进行Mock的:

@Runwith(springRunner.class)

@springBootTest

public class xxx{

@AutoWired

XXXXXservice  xxxservice;


@Test
public void test1(){

new MockUp<测试类> {
   @mock
   private String XXX(){
     return "";
   }

   @mock 
   public String xxx(){
     return "";
   }

   @mock 
   public Int xxx(){
     return x;
   }
  }.getInstance()

   AssertEqual(xxx, xxxservice.XXX());

   //防止被mock的方法再被调用的时候出现干扰
   Mockup.teardown();
}

4.prameter的Mock方法:

①泛型类作为参数时,举例:User.java,Mockito.any(User.class)即可;

②string作为参数时,Mockito.anyString()可;

③NULL作为参数时,Mockito.any()可(Mockito.any()或许也可用于其他的很多类型参数);

④int和Integer类,Mockito.anyInt();    Mockito.any(int.class) ?

以上均是回忆的内容,可能出现偏差,实际为主。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值