简体   繁体   English

如何从可测试类中模拟调用方法?

[英]How do I mock call method from testable class?

Want to ask you a question. 想问你一个问题。

How should I properly return some data from method called from testable class ? 我应该如何从可测试类调用的方法中正确返回一些数据?

For example I have next structure: 例如,我有下一个结构:

Class SomeClass {
    public void method1(){
    //some logic here
    List<Object> howToReturnHereValues = gatData();
    //some logic here
    }
    public List<Object> getData(){

       return List<Object>;

    }
}

Right now I want to test method1() , but I don't know how to mock call getData() which returns List<Object> . 现在我想测试method1() ,但我不知道如何模拟调用getData()返回List<Object>

Any advice please ? 有什么建议吗?

Right now I want to test method1(), but I don't know how to mock call getData() which returns List. 现在我想测试method1(),但我不知道如何模拟调用getData()返回List。

It is rather a bad idea to mock a public method of a class that is under test. 模拟正在测试的类的公共方法是一个坏主意。

A unit test should test a behavior and mock dependencies. 单元测试应测试行为和模拟依赖项。 Here, you unit test only a part of the behavior as you mock the behavior of the tested class. 在这里,您在模拟测试类的行为时仅对行为的一部分进行单元测试。

If the class is ours you could : 如果课程是我们的,您可以:

  • either test this method without mocking the getData() called public method. 要么在不模仿getData()调用公共方法的情况下测试此方法。
  • or move the getData() public method in another class and then mock this new dependency if you don't want to repeat the test of the getData() method in each test method calling it. 或者将getData()公共方法移动到另一个类中,如果你不想在每个调用它的测试方法中重复getData()方法的测试,那么就模拟这个新的依赖项。

If the class is not modifiable and the mocked called is really required, you could use the spy() method of the Mockito framework on the object under test to simulate a mocked behavior for a specific method. 如果类不可修改且实际需要模拟调用,则可以在测试对象上使用Mockito框架的spy()方法来模拟特定方法的模拟行为。

You can do this using a spy, like explained here: https://static.javadoc.io/org.mockito/mockito-core/2.7.17/org/mockito/Mockito.html#13 您可以使用间谍来执行此操作,如下所述: https//static.javadoc.io/org.mockito/mockito-core/2.7.17/org/mockito/Mockito.html#13

Example: 例:

@Test
public void testMethod1() throws Exception {
    SomeClass someClass = new SomeClass();
    SomeClass spy = Mockito.spy(someClass);
    Mockito.when(spy.getData()).thenReturn(Arrays.asList("blaat", "blabla"));
    spy.method1();
}

This will return a List of "blaat" and "blabla" which can be used by the logic in your method1. 这将返回一个“blaat”和“blabla”列表,可以由method1中的逻辑使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM