使用Mockito注释与spring

rah*_*hul 8 java spring mockito

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

可以说我有以下场景

这是我的webservice接口

public interface MyWebService {
    public String getSomeData(int id);
}
Run Code Online (Sandbox Code Playgroud)

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

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("..");
    }
}
Run Code Online (Sandbox Code Playgroud)

我写了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();
    }

}
Run Code Online (Sandbox Code Playgroud)

当我运行测试时,我看到的是,我从网络服务中得到了我在提交时提到的内容.

谁能帮我这个?

rah*_*hul 6

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

    @Configuration
    public class TestConfig extends DefaultConfig {

      @Bean
      public MyService myService() {
        return Mockito.spy(new MyServiceImpl());
      }
    }
Run Code Online (Sandbox Code Playgroud)

现在我的测试课就是这样的

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

}
Run Code Online (Sandbox Code Playgroud)