Reputation: 1712
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.
Upvotes: 2
Views: 794
Reputation: 16380
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);
}
}
Upvotes: 0
Reputation: 1757
You should avoid creating instances of classes which have any logic inside (not plain DTO objects). Instead you should design your classes in such a way that dependency injection container can build up complete graph of objects. In your code you need to answer yourself if each call of authenicate
method does need a new instance of AuthenticationServicePort
? If yes then you should use a factory pattern to create instances of this object and this factory should be injected (provided in constructor) so you can mock it and everything it will produce. If many calls of authenticate
method can reuse same instance of AuthenticationServicePort
then simply inject it (provide in constructor) and in your test provide mock instead of real implementation.
Upvotes: 1