microsoft / azure-devops-intellij

IntelliJ IDEA plug-in for Visual Studio Team Services and Team Foundation Server (TFS)
MIT License
149 stars 94 forks source link

Refactor to Eliminate Repetitive Mock Object Creation in LookupHelper #583

Open gzhao9 opened 3 weeks ago

gzhao9 commented 3 weeks ago

Hi there!

While working with the LookupHelper class, I noticed two mock variables repeatedly created across various tests. To simplify the code, I propose a small refactor to eliminate these redundancies, which could reduce the code by 30 lines.

  1. Repetitive Mock AuthenticationProvider Creation: The creation of a mock AuthenticationProvider object repeated in 9 test cases.

  2. Repetitive Mock LoginPageModel Creation: The creation of a mock LoginPageModel object repeated in 12 test cases.

Specifically, here is the refactoring method I propose:

Creating a mock for AuthenticationProvider currently looks like this:

   final AuthenticationProvider authenticationProvider = Mockito.mock(AuthenticationProvider.class); // Before Refactoring
   when(authenticationProvider.isAuthenticated(serverUrl)).thenReturn(Auth); // Before Refactoring
   doNothing().when(authenticationProvider).authenticateAsync(anyString(), any(AuthenticationListener.class)); // Before Refactoring

I introduced a method, createMockAuthenticationProvider:

   AuthenticationProvider createMockAuthenticationProvider(String serverUrl, boolean Auth) {
       AuthenticationProvider authenticationProvider = Mockito.mock(AuthenticationProvider.class);
       when(authenticationProvider.isAuthenticated(serverUrl)).thenReturn(Auth);
       doNothing().when(authenticationProvider).authenticateAsync(anyString(), any(AuthenticationListener.class));
       return authenticationProvider;
   }

With this method, creating a mock AuthenticationProvider becomes:

   final AuthenticationProvider authenticationProvider = createMockAuthenticationProvider(serverUrl, false);

Similarly, for LoginPageModel, I introduced a method, createMockLoginPageModel as follows:

   LoginPageModel createMockLoginPageModel(String serverUrl) {
       LoginPageModel loginPageModel = Mockito.mock(LoginPageModel.class);
       when(loginPageModel.getServerName()).thenReturn(serverUrl);
       return loginPageModel;
   }

This is the code before the refactoring:

   final LoginPageModel loginPageModel = Mockito.mock(LoginPageModel.class); // Before Refactoring
   when(loginPageModel.getServerName()).thenReturn(serverUrl); // Before Refactoring

This is the code after the refactoring:

   final LoginPageModel loginPageModel = createMockLoginPageModel(null);

The refactor reduced the test cases by 30 lines of code, and I believe these changes will improve code readability.