Search code examples
javaunit-testingjunitmockingjmockit

How to Write TestCase in Java for this Service?


I have a this class

public class AuthenticationModule {

    String userName = "foo";
    String password = "bar";

    public void setUserName(String userName) {
         this.userName = userName;
    }

    public void setPassword(String password ) {
         this.password = password ;
    }

    AuthenticationServicePort authenticationServicePort;
    AuthenticationService port;

    private boolean authenicate(String userName, String password) {

        authenticationServicePort = new AuthenticationServicePort();
        port = authenticationServicePort.getAuthenticationServiceProxy();
        return port.login(userName, password);
    }

    public boolean validateUser() {

        return authenicate(userName, password);
    }
}

and AuthenticationServicePort returns a WSDL port I want to create a simple test case with a Mock AuthenticationServicePort which will return a 'true/false' value

How do I inject in my own MockObject without changing the java code? Or worse case scenario, what is the easiest way to change to be be more easily testable.


Solution

  • Here is an example test where AuthenticationServicePort is mocked, using JMockit 1.13:

    public class AuthenticationModuleTest
    {
        @Tested AuthenticationModule authentication;
        @Mocked AuthenticationServicePort authenticationService;
        @Mocked AuthenticationService port;
    
        @Test
        public void validateUser()
        {
            final String userName = "tester";
            final String password = "12345";
            authentication.setUserName(userName);
            authentication.setPassword(password);
            new Expectations() {{ port.login(userName, password); result = true; }};
    
            boolean validated = authentication.validateUser();
    
            assertTrue(validated);
        }
    }