I have some confusion about DI in spring
public interface A{
void methodA();
}
public class AImpl implements A{
public void methodA(){
// todo something
}
}
public interface B{
void methodB();
}
public class BImpl implements B{
public void methodB(){
//todo somethong
}
}
I have two interface A and B and 2 class implements it. So, I have 2 Class that implement interface C, it depend on Interface A and B
This is case 1:
public interface C{
void methodC();
}
public class CAutowired implements C{
@Autowired
private A a;
@Autowired
private B b;
public void methodC(){
a.methodA();
b.methodB();
}
}
File .xml config
<beans>
<bean id="classA" class="com.example.AImpl" />
<bean id="classB" class="com.example.BImpl" />
<bean id="classC" class="com.example.CAutowired" />
<beans>
In this case, i have a question: - How to Mock A and B when i write unitTest for class CAutowired
This is case 2:
public class CInitInject implements C{
private A a;
private B b;
public CInitInject(A a, B b){
this.a = a;
this.b = b;
}
public void methodC(){
a.methodA();
b.methodB();
}
}
File .xml config
<beans>
<bean id="classA" class="com.example.AImpl" />
<bean id="classB" class="com.example.BImpl" />
<bean id="classC" class="com.example.CInitInject">
<constructor-arg ref="classA" />
<constructor-arg ref="classB" />
</bean>
<beans>
In this case, i get DI method the same in .NET. I can Mock A and B by inject into constructor. Example:
@Mock
private A aMock;
@Mock
private B bMock;
private C c;
public void setUp(){
c = new CInitInject(aMock, bMock);
}
@Test
public void test(){
// todo Test somemethod
}
End of all, I have a question
- What is best practice between case 1 and case 2?
- How to Mock it when unit test
Aucun commentaire:
Enregistrer un commentaire