2

我有一堂课如下:

@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 服务调用。那么如何模拟 Web 服务,当我调用类的身份验证方法时,使用模拟的 Web 服务对象而不是真实的对象。

4

2 回答 2

1

Using Mockito you stub the external service like this:

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

I am writing this up from memory so forgive if it doesn't compile straight away; you'll get the idea.

Here, using Mockito, hamcrest and JUnit 4, I am also verifying that the service is called with the correct parameters, which your test will want to cover as well :)

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

Lastly, the fact that your class is @Autowired makes no difference to any of this.

于 2013-05-24T13:53:45.227 回答
1

您应该@ContextConfiguration在测试类中使用注释。

这样做 Spring 将从classpath:/foo.bar/spring/test/...xml

在该context.xml文件中,/test/您可以创建模拟对象,Spring 将注入它们而不是真实的。

如果您需要分步指南,您可以找到许多教程,只需搜索Spring @ContextConfiguration(我不包含链接,因为它们可能会及时更改)。

于 2013-05-24T12:33:31.483 回答