有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用Mockito/EasyMock模拟自动连接的Web服务

我的课程如下:

@Component
public class UserAuthentication {

    @Autowired
    private AuthenticationWebService authenticationWebservice;

    public boolean authenticate(username, password) {

    result = authenticationWebService.authenticateUser(username, password)

    //do
    //some
    //logical
    //things
    //here

    return result;
   }
}

我正在写一个单元测试,看看函数是否正确运行。当然,现在我不打算进行真正的Web服务调用。那么,我如何模拟webservice,以便在调用类的authenticate方法时,使用模拟的webservice对象而不是真实的webservice对象呢


共 (1) 个答案

  1. # 1 楼答案

    使用Mockito,您可以如下方式存根外部服务:

    'when(mockedAuthenticationWebService.authenticate(username, password).thenReturn(yourStubbedReturnValue);'
    

    我是凭记忆写这篇文章的,所以如果它没有立即编译,请原谅;你会明白的

    在这里,我还使用Mockito、hamcrest和JUnit 4验证了使用正确的参数调用服务,这也是您的测试想要涵盖的:)

    @Test
    public class UserAuthenticationTest { 
         // Given 
         UserAuthentication userAuthentication = new UserAuthentication(); 
         AuthenticationWebService mockedAuthenticationWebService = mock(AuthenticationWebService.class)
    
         String username = "aUsername" , password = "aPassword";
         when(mockedAuthenticationWebService.authenticate(username, password).thenReturn(true); // but you could return false here too if your test needed it
    
         userAuthentication.set(mockedAuthenticationWebService); 
    
         // When  
         boolean yourStubbedReturnValue = userAuthentication.authenticate(username, password); 
    
         //Then 
        verify(mockedAuthenticationWebService).authenticateUser(username, password); 
        assertThat(yourStubbedReturnValue, is(true));
    }
    

    最后,你的类是@Autowired这一事实对这一切都没有影响