问题描述
我有 class1 类,它有 2 个成员变量:
classA
{
private Boolean isEnable;
private Config config;
public classA(final Config config)
{
this.config = config;
isEnable = config.getEnablingStatus();
}
public classB fun()
{
// Do something!
// Return an object of classB!
}
}
我想测试方法有趣,所以我必须为此编写一个测试类和一个测试方法。但是,如何在测试类中创建 classA 类型的对象时模拟方法调用 config.getEnablingStatus()?
我正在考虑做这样的事情[见下面的代码]。它正确吗?但正确的做法是什么?
TestClassForClassA:
TestClassForClassA
{
private Boolean isEnable;
@Mock
private Config config;
@InjectMocks
classA objA = new classA(config);
@Before
public void init()
{
initMocks(this);
}
public void test1Fun()
{
// Does doing this,put the value of isEnable as true in the objA for this test?
isEnable = true;
// Here write the code to test the method fun().
}
public void test2Fun()
{
// Does doing this,put the value of isEnable as false in the objA for this test?
isEnable = false;
// Here write the code to test the method fun().
}
}
解决方法
不要使用@InjectMocks
尝试这样的事情
public class TestClassForClassA {
@Mock
private Config config;
private ClassA objA;
@Before
public void init() {
MockitoAnnotations.initMocks(this);
}
@Test
public void test1Fun() {
Mockito.when(config.getEnablingStatus()).thenReturn(true);
objA = new ClassA(config);
ClassB objB = objA.fun();
assertTrue(objB.isEnabled());
}
@Test
public void test2Fun() {
Mockito.when(config.getEnablingStatus()).thenReturn(false);
objA = new ClassA(config);
ClassB objB = objA.fun();
assertFalse(objB.isEnabled());
}
}