java 在 spring 中使用 Mockito 注释

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15635365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 20:19:58  来源:igfitidea点击:

Using Mockito annotations with spring

javaspringmockito

提问by rahul

I am using spring in my application and I want to write unit tests for all my classes. I call few external webservices from my application and i want to mock them using Mockito since I just want to test my functionality.

我在我的应用程序中使用 spring,我想为我的所有类编写单元测试。我从我的应用程序中调用了几个外部网络服务,我想使用 Mockito 来模拟它们,因为我只想测试我的功能。

Lets say I have the following scenario

假设我有以下场景

This is my webservice interface

这是我的网络服务界面

public interface MyWebService {
    public String getSomeData(int id);
}

I use the above service this way

我以这种方式使用上述服务

public interface MyService {
    int doSomethingElse(String str);
}

public class MyServiceImpl implements MyService {

    private MyWebService myWebService;

    int doSomethingElse(String str) {
        .....
        myWebService.getSomeData(id);
        ...
    }
}

public interface MyService1 {
    Stirng methodToBeTested();
}


public class Class1 implements MyService1{
    @Resource
    private MyService myService;

    public Stirng methodToBeTested() {
        myService.doSomethingElse("..");
    }
}

I wrote the uint test case as below. I am spying MyService here so as to run the unit test.

我编写了 uint 测试用例,如下所示。我在这里监视 MyService 以便运行单元测试。

public class class1Test {

    @Spy
    MyService myService;

    @Resource
    @InjectMocks
    Class1 class1;

    public void setUPTest() {
        MockitoAnnotations.initMocks(this);
    Mockito.doReturn(123).when(myService).doSomethingElse("someString");
    }

    @Test
    public void methodToBeTestedTest() {
        this.setUPTest();
            ...
            class1.methodToBeTested();
    }

}

When I run the test, what I see is that, I get the value from the webservice insted of what i mention while stubbing.

当我运行测试时,我看到的是,我从网络服务中获得了我在存根时提到的内容的价值。

Can anyone help me with this?

谁能帮我这个?

采纳答案by rahul

I solved this by using spring java config. I extended my default config file in my test config file.

我通过使用 spring java config 解决了这个问题。我在我的测试配置文件中扩展了我的默认配置文件。

    @Configuration
    public class TestConfig extends DefaultConfig {

      @Bean
      public MyService myService() {
        return Mockito.spy(new MyServiceImpl());
      }
    }

Now my test class goes like this

现在我的测试课是这样的

public class class1Test {

    @Resource
    MyService myService;

    @Resource
    Class1 class1;

    public void setUPTest() {
        MockitoAnnotations.initMocks(this);
    Mockito.doReturn(123).when(myService).doSomethingElse("someString");
    }

    @Test
    public void methodToBeTestedTest() {
        this.setUPTest();
            ...
            class1.methodToBeTested();
    }

}

回答by Michail Nikolaev

To replace your Bean with mock in some test use Springockitoor better Springockito-annotations.

要在某些测试中用模拟替换 Bean,请使用Springockito或更好的Springockito-annotations

Something like this should work:

这样的事情应该工作:

@ContextConfiguration(loader = SpringockitoContextLoader.class,
    locations = "classpath:/context.xml")
public class SpringockitoAnnotationsMocksIntegrationTest extends AbstractJUnit4SpringContextTests {

    @WrapWithSpy
    private MyService innerBean;

    @Resource  
    Class1 class1;

    public void setUPTest() {        
        Mockito.doReturn(123).when(myService).doSomethingElse("someString");
    }

    @Test
    public void methodToBeTestedTest() {
    this.setUPTest();
        ...
        class1.methodToBeTested();
    }

}

}

回答by Anders R. Bystrup

A @Spyis used to spy on what happens when calling services (and useful to eg. assert the presence or absence of transitive method invocations), what you want is the @Mockannotation:

A@Spy用于监视调用服务时发生的情况(并且有助于例如断言传递方法调用的存在或不存在),您想要的是@Mock注释:

public class class1Test {
    @Mock MyService myService;
    ...

This will result in all myServicemethods returning null, bar those you override with doReturn/when.

这将导致所有myService方法返回 null,禁止使用doReturn/覆盖的方法when

Incidentally, rather than calling setUpTest()from your test methods, you should annotate it with @Before.

顺便说一句,与其setUpTest()从测试方法中调用,不如用@Before.

Cheers,

干杯,

回答by OceanLife

Do you mean anyString()rather than "someString" in your setUpmethod? This can also be eq("someString")if you are calling your method with a specific string.

你的意思是anyString()而不是你的setUp方法中的“someString” ?eq("someString")如果您使用特定字符串调用您的方法,也可能是这种情况。

From my understanding of Mockito I don't use spys since they probably indicate a class design issue. Why don't you @Mockthe whole of MyService, so;

根据我对 Mockito 的理解,我不使用间谍,因为它们可能表明存在类设计问题。你为什么不@Mock整个MyService,所以;

@Mock MyService myService;


public void setUpTest() {
    MockitoAnnotations.initMocks(this);
    when(myService.doSomethingElse(anyString)).thenReturn(123);
}

回答by Sajan Chandran

Modified,

修改的,

    public class class1Test {

    @Mock
    private MyService myService;

    private Class1 class1;

    @Before
    public void onceBeforeEachTest() {
        MockitoAnnotations.initMocks(this);
         this.class1 = new Class1(myService); 
        Mockito.when(myService).doSomethingElse(anyString()).thenReturn(123);
    }

    @Test
    public void methodToBeTestedTest() {
            class1.methodToBeTested();
    }
}

回答by Sajan Chandran

This should suits your need:

这应该适合您的需要:

@RunWith(MockitoJunitRunner.class)
public class class1Test {

    @Mock
    private MyService myService;

    private Class1 class1;

    @Before
    public void setUp() {
        this.class1 = new Class1(myService); // creates this constructor.
    }

    @Test
    public void methodToBeTestedTest() {
        this.class1.methodToBeTested();
        Mockito.verify(this.myService).doSomethingElse(/* put expected arg here */);
    }
}

See also the official doc.

另请参阅官方文档