Pergunta

I am facing problem while creating junit test cases for a method which contains below code .

I have to bypass this line using mock object.

SecurityContextHolder.getContext().getAuthentication().getPrinciple();

please help me to create mock object for this method chains, any suggestion/ideas are most welcome.

thanks in advance..

Foi útil?

Solução 2

Another way is to delegate the code i.e.:

SecurityContextHolder.getContext().getAuthentication().getPrinciple()

to another object, e.g.:

AuthenticationService

then auto-wire the service in your code. you can then mock the service in your test.

Hope that helps.

Outras dicas

You may be out of luck if you need to use Mockito - it can't mock static methods, which is the first thing you need to do in calling static method getContext() on SecurityContextHolder.

An alternative that may be able mock that first call is powermock. If you can get past the first static method, mocking the rest of the chain will probably involve mocking the return value of each call and setting up the chain by hand, for example, creating a mock Authentication instance to be returned by your mock SecurityContext instance, and so on.

As @Brabster said, you can't mock static methods. If you still want to use mockito, you'll need to find a way to mock what getContext() returns. This can be done by modifying the system under test to give it a test mode. When it's in that test mode, you can call a setter to set the return value to a mockito mock. Or you can combine these steps by adding a setTestContext(...) method to the class.

See how this is annoying to write? That's because the code you're trying to test is bad, not because mockito is missing a feature. Mockito is pointing out a code smell.

You can do this by using Mockito as a spy

Wrap the static method call in a another method

e.g

  public User getUser()
 {
    return (User)SecurityContextHolder.getContext().getAuthentication().getPrinciple();
 }

Then create a spy of your object under test and you can mock the getUser method.

see http://eclipsesource.com/blogs/2011/10/13/effective-mockito-part-3/

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top