2017-02-21 37 views
0

我有两个类:嘲笑值不退还

public class Foo { 
    public int getInt(){ 
     return 10; 
    } 
} 

public class Bar { 
    Foo testClass = new Foo(); 

    public Foo getTestClass() { 
     return testClass; 
    } 

    public void setTestClass(Foo testClass) { 
     this.testClass = testClass; 
    } 

    public int get(){ 
     return testClass.getInt(); 
    } 
} 

最后,我有测试类模拟为富:

​​

你能告诉我,为什么我从得到10 t.get()虽然在模拟“我说”,我想要5?

我该如何写Mock来获得嘲讽价值?

在此先感谢。

+0

看来你的模拟没有设置。 – Mistalis

回答

1

你忘了实际上你的模拟电话t.setTestClass(test);

+0

如果方法setTestClass将被保护怎么办?现在我不能使用t.setTestClass – Cwaniak

+0

然后你可以改变你的构造函数从那里注入模拟,或者你可以通过反射使得setter可用。 – QBrute

0

当你写:

public class TestClass { 

    Foo test; 

    @Before 
    public void init(){ 
     test = Mockito.mock(Foo.class); 
     Mockito.when(test.getInt()).thenReturn(5); 
    } 

    @Test 
    public void tst(){ 
     Bar t = new Bar(); 
     Assert.assertEquals(t.get(), 5); 
    } 
} 

你嘲笑你Foo类,但不是在Bar类使用它。所以,如果你打电话给退货方法,它不会发送你试图模拟的结果