I have something like this:
public class Class1 {
@Autowired
Class2 class2;
public Object class1Method {
// Do something
Object obj = class2.class2Method(arg);
// Do something with obj
return somthing;
}
}
I am doing unit testing to Class1 and I want to mock the class2Method. I tried to find solution and I found this:
Test class with a new() call in it with Mockito
I understood that this solution works if I do new instance of Class2 in the class1Method, but in my case I use Spring Dependency Injection and I can't figure out how to this.
Depending on how did you build your DI with spring you can use something like this if you have @Autowired on field
@RunWith(SpringRunner.class)
public Class1Test {
@InjectMocks
@Autwired
private Class1 class1;
@Mock
Class2 class2;
@BeforeMethod
public void initMocks(){
MockitoAnnotations.initMocks(this);
}
@Test
public Object testClass1Method {
when(class2.class2Method(anyString()).thenReturn(expectedReturn);
//Now test whatever you need with mocked class2.class2Method
}
}
It's much easier and you don't need to have spring context up for tests if you have constructor DI (@Autowired on constructor)
public Class1Test {
private Class1 class1;
private Class2 class2;
@BeforeMethod
public void initMocks(){
class2 = mock(Class2.class);
class1 = new Class1(class2);
}
//then use the same approach to mock any methods that you need
}
You should go with
Mockito
,and have your JUnit class include this at the top @RunWith(MockitoJUnitRunner.class). So in your case you can have your Junit like this.
@RunWith(MockitoJUnitRunner.class)
public Class1Test {
@InjectMocks
private Class1 class1 = new Class1();
@Mock
Class2 class2;
@Test
public Object testClass1Method {
// Now this will get the class2 mock instance when executed
Object obj = class1.class1Method(arg);
}
}
This is how you can write Unit test for Class1 using Mockito :
public Class1Test {
@InjectMocks
private Class1 class1;
@Mock
private Class2 class2;
@BeforeMethod
public void initMocks(){
MockitoAnnotations.initMocks(this);
}
@Test
public void test_method1() {
Object obj = //instantiate it here...,
Mockito.doReturn(obj).when(class2.class2Method(anyString());
Assert.assertEquals(class1.class1Method(), something);
}
}