当相同的参数具有不同的结果时,mockito是什么? [英] Mockito when same parameter with different result?

查看:101
本文介绍了当相同的参数具有不同的结果时,mockito是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有build()功能的builder类,我正在为其提供服务.

I have a builder class that has build() function, I'm passing a service for it.

我为构建器提供了一个测试类,该类具有两种方法

I have a test class for the builder which has two methods

是否可以使用相同的参数两次测试相同的参数,但是返回不同的值?

Is there a way to test the same with the same parameter twice but returning a different value?

@Before
public void initTest() {
    MockitoAnnotations.initMocks(this);
}

@Test
private void test1{
    Mockito.when(defaultBuilder.build(service)).thenReturn(createObject());
}

@Test
private void test2(){  
    Mockito.when(defaultBuilder.build(service)).thenReturn(createDifferentObject());
}   

问题是即使我期望使用createDifferentObject(),我还是从第二次测试中获得了createObject()对象.

The problem is I get the createObject() object from second test, even though I'm expecting createDifferentObject().

推荐答案

    public class Test {

    private MyObject myobject;
    private MyObject myDifferentObject;

    @Before
    public void initTest() {
        MockitoAnnotations.initMocks(this);
    myobject=createObject();
    myDifferentObject=createDifferentObject();
    }

    @Test
    private void test1{
        Mockito.when(defaultBuilder.build(service)).thenReturn(myobject);
    }

    @Test
    private void test2(){  
        Mockito.when(defaultBuilder.build(service)).thenReturn(myDifferentObject);
    }     

    }

//should work.

这篇关于当相同的参数具有不同的结果时,mockito是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆