Testowanie

0

Mam problem z mockowaniem (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication(); tej cześć kodu kontrolera
wyrzuca ten błąd. Przypuszaczam, że powodem jest klasa statyczna. Może ma ktoś pomysł jak to zrobić>
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);

Also, this error might show up because:

  1. you stub either of: final/private/equals()/hashCode() methods.
    Those methods cannot be stubbed/verified.
    Mocking methods declared on non-public parent classes is not supported.
  2. inside when() you don't call method on mock but on some other object

Kontroller

	public Model createArticlePath(Model model) {
		 UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
		 LdapUserDetailsImpl principal = (LdapUserDetailsImpl) authentication.getPrincipal();
	     model.addAttribute("userName" , principal.getUsername());
	     model.addAttribute("role", principal.getAuthorities());
		return model;
	}

	@GetMapping(value = artykul)
	public String ArticleManager(Model model, @RequestParam(required = false) String message) {
		List<Article> articleList = articleService.getAllArticle();
		model.addAttribute("articleList", articleList);
		
		if(message != null) {
			model.addAttribute("isArticleDeleted", false);
		}
		
		return "artykul";
	}

Test

public class ArticleManagerControllerTest {
	
	@Autowired
    private MockMvc mockMvc;	
	@InjectMocks
	private ArticleManagerController articleManagerController;	
	@Mock
	private ArticleService articleService;
	@Mock
	private Authentication authentication;
	@Before
	public void setUp() throws Exception {
	    mockMvc = MockMvcBuilders.standaloneSetup(articleManagerController)
                 .setViewResolvers(new InternalResourceViewResolver("", ".html"))
                 .build();
	}

	@After
	public void tearDown() throws Exception {
	}

	@Test
	public void testArticleManager() throws Exception {
		List<Article> articleList = new ArrayList<>();	
		Article article = new Article();
		articleList.add(article);
		LdapUserDetailsImpl mockLdapUserDetailImp = new MockLdapUserDetailImp();
		UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =new UsernamePasswordAuthenticationToken(new Object(), new  Object());
		Mockito.when(SecurityContextHolder.getContext().getAuthentication()).thenReturn(usernamePasswordAuthenticationToken);
		when(authentication.getPrincipal()).thenReturn(mockLdapUserDetailImp);
		when(articleService.getAllArticle()).thenReturn(articleList);
		  mockMvc.perform(get("artykul"))
				  .andExpect(status().is(200))
				  .andExpect(view().name("artykul/artykul"))
	}
1

Jeśli uczysz się Javy, to uciekaj od Springowych widoków. Nie przyda ci sie i jeszcze namiesza w głowie. Zamiast tego zrób kontrollery RESTowe.

Twoim problemem jest to, że klasa jest nietestowalna. Żeby mockować metody statyczne potrzebujesz ciężkiego artylerii, jak np. PowerMockito. Ale to narzędzie służy do walki z legacy code, ale tak se o.
Zamiast tego, zrób tak, żeby klasa była testowalna. Użyj na przykład mega super patternu jak Dependency Injection.
Czyli w metodzie createArticlePath zamiast samemu wydobywać token, to... przekaż sobie w parametrze.
Wtedy w metodzie ArticleManager będzie potrzebował tokena, więc... przekaż sobie w parametrze. Uwaga, uwaga. Spring wspiera przekazywanie principala w paramerze metody kontrollera (nawiasem mówiąc używaj javowej konwencji nazewnictwa. Metody piszemy camelCasem)

Jeśli się nie będzie dało (I TYLKO JAK SIĘ NIE BĘDZIE DAŁO), to zrób sobie serwis, który zajmuje się pozyskiwaniem usera, czy czego tam bedziesz w przyszlosci potrzebował. I wstrzyknij serwis. Obiekt normalnie możesz zamockować. Przy okazji podzielisz odpowiedzialności na dwie klasy.

1 użytkowników online, w tym zalogowanych: 0, gości: 1