Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/docker/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 未返回模拟值_Java_Mocking_Mockito - Fatal编程技术网

Java 未返回模拟值

Java 未返回模拟值,java,mocking,mockito,Java,Mocking,Mockito,我有两门课: 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) { th

我有两门课:

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();
    }
}
最后,我用mock for Foo创建了一个测试类:

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);

    }
}
你能告诉我,为什么我从t.get()得到10,尽管在模拟的“我说”中我想要5

如何编写Mock以获得Mock值


提前感谢。

您忘记了通过调用
t.setTestClass(test)来实际设置mock

当您在编写时:

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
类,但没有在
栏中使用它。因此,如果您调用return方法,它将不会发送您试图模拟的结果,因为您的模拟似乎未设置。如果方法setTestClass将受到保护,该怎么办?现在我不能使用t.settestclasse,那么您可以更改构造函数以从那里注入mock,或者通过反射使setter可访问。