没有调用模拟方法

时间:2018-03-10 06:40:13

标签: mockito

public class Employee { 

    public void getAddress(){
        Address add = new Address();
        String a = add.addAddress();
        System.out.println(a);
    }
}


public class Address {

    public String addAddress(){
        return "Emp Address";
    }
}

public class MockitoTest {

    @Mock
    Address add;

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


    @Test
    public void testEmployee(){
        when(add.addAddress()).thenReturn("mocked address");
        Employee e = new Employee();
        e.getAddress();

    }
}

在上面的例子中,我想在地址类中模拟addAddress()方法。当我运行mockito时,它调用真实方法addAddress()而不是模拟的方法并打印" Emp Address",而不是"模拟地址"。我需要"模拟地址"作为输出。

1 个答案:

答案 0 :(得分:0)

问题是@pvpkiran在问题评论中提到的。如果您想要模拟行为,则需要提供规定以将模拟的expectedBy project(':module2')对象传递给Address

一种方法是

Employee

编辑:使用Powermock(使用public class Employee { public void getAddress(Address add) { String a = add.addAddress(); System.out.println(a); } } public class MockitoTest { @Mock Address add; @Before public void setup(){ MockitoAnnotations.initMocks(this); } @Test public void testEmployee(){ when(add.addAddress()).thenReturn("mocked address"); Employee e = new Employee(); e.getAddress(add); } } 测试)

org.powermock:powermock-mockito-release-full:1.6.4