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?
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.
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With