Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test class with a new() call in it with Mockito

I have a legacy class that contains a new() call to instantiate a LoginContext object:

public class TestedClass {   public LoginContext login(String user, String password) {     LoginContext lc = new LoginContext("login", callbackHandler);   } } 

I want to test this class using Mockito to mock the LoginContext as it requires that the JAAS security stuff be set up before instantiating, but I'm not sure how to do that without changing the login() method to externalize the LoginContext.

Is it possible using Mockito to mock the LoginContext class?

like image 203
bwobbones Avatar asked May 07 '11 09:05

bwobbones


People also ask

How do you write a test class in Mockito?

The following steps are used to create an example of testing using Mockito with JUnit. Step 1: Create an interface named ToDoService that contains an unimplemented method. Step 2: Now, create an implementation class named ToDoBusiness for ToDoService interface.

How do you unit test classes which create new objects?

The first step is to import Mockito dependencies into your code. Now let us see an example of how to test the class. Let us assume the below is the class that we want to test. Below is the sample class of the object that is instantiated in ClassToBeTested.

How do you mock a method inside a class?

We can mock runInGround(String location) method inside the PersonTest class as shown below. Instead of using mock(class) here we need to use Mockito. spy() to mock the same class we are testing. Then we can mock the method we want as follows.

Can Mockito mock a class?

The Mockito. mock() method allows us to create a mock object of a class or an interface. We can then use the mock to stub return values for its methods and verify if they were called.


1 Answers

For the future I would recommend Eran Harel's answer (refactoring moving new to factory that can be mocked). But if you don't want to change the original source code, use very handy and unique feature: spies. From the documentation:

You can create spies of real objects. When you use the spy then the real methods are called (unless a method was stubbed).

Real spies should be used carefully and occasionally, for example when dealing with legacy code.

In your case you should write:

TestedClass tc = spy(new TestedClass()); LoginContext lcMock = mock(LoginContext.class); when(tc.login(anyString(), anyString())).thenReturn(lcMock); 
like image 115
Tomasz Nurkiewicz Avatar answered Oct 13 '22 06:10

Tomasz Nurkiewicz