2

I know this question has been answered by others before, but the answer seems to be different depending on the situation.

I see many people saying the class should be instantiated, so that it can be tested and mocked etc... Well here's my code and it looks to me like I could easily unit test it.

WebsiteLogin.java Is an interface which extends Website.java and contains a void method called login(), it takes three strings, Username, Password and Url.

AccountLogin.java Is an interface which extends Account and contains getter methods for Username, Password and Url, as well as a setEnabled() method which takes a boolean.

In a seperate class called Login.java I have a method login() which takes WebsiteLogin and AccountLogin. The class only has the one method.

Here's the code

static void login(AccountLoginInformation account, LoginToWebsite website){
        website.login(account.getUsername(), account.getPassord(), account.getUrl());
        account.setEnabled(true);
}

So it logs in and then sets the account to enabled. Now although this method is static, I could still test it works by sending a stubbed LoginToWebsite to it. Am I correct here? So would there be any other reason for not using a static method?

Another question, with Java 8 and default methods in interfaces, could I create an interface called Login.java with the following;

default void login(AccountLoginInformation account, LoginToWebsite website){
        website.login(account.getUsername(), account.getPassord(), account.getUrl());
        account.setEnabled(true);
}

Then in another class implement the Login.java class and just call

login(account, website);

Or is this bad practice?

Adam.J
  • 2,519
  • 3
  • 14
  • 12
  • Methods are not 'instantiated', but they can be *instance methods.* They normally are instance methods, unless you have a god reason for making them static. – user207421 Nov 04 '15 at 21:22
  • Haha yeah I meant instantiate the class they are in to use them. My bad, will edit – Adam.J Nov 04 '15 at 21:28
  • The problem with static methods is not that it's difficult to test them. Testing them is no problem. The problem is that it's difficult to test **other** methods that **use** the static method. Because you can't easily stub the static method, but you can easily stub an instance method. – JB Nizet Nov 04 '15 at 21:50

0 Answers0