Montag, 29. April 2019

Spring Security - get User Name

If you want to retrieve the name of  a logged in user, do this:


import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
private String getUserName() {
    Object principal = SecurityContextHolder
          .getContext()
          .getAuthentication()
          .getPrincipal();

    String userName;

    if (principal instanceof UserDetails) {
        userName = ((UserDetails)principal).getUsername();
    } else {
        userName = principal.toString();
    }
    return userName;
}

Mittwoch, 24. April 2019

Recover and Restore System Properties with Java - JUnit and more - Free program

Sometimes it is necessary to change System Properties. Maybe for a Test or something else. This program and test will recover and restore the System Properties to their initial state.
The program and test may be used freely under GNU General Public License Version and is brought to you by Harder IT Consulting www.harder-it-consulting.de
  

Mittwoch, 17. April 2019

Mock static methods with Mockito in Java (mock, static, method, java)


import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.BDDMockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;


@RunWith(PowerMockRunner.class)
@PrepareForTest(MyStatic.class)
...


@Test
public void someTest() {
    
    //given    
    PowerMockito.mockStatic(MyStatic.class);
    BDDMockito.given(MyStatic.someStaticMethod()).willReturn(...);

    //when
    ...

    //then     
    PowerMockito.verifyStatic();
    MyStatic.someStaticMethod();

    assertThat(//your further asserts....

NEW BLOG! http://cleancode.consulting/

Dear Reader, This Blog is closed and remains as an archive. Please find our new Blog at  http://cleancode.consulting/