Mockito Mock运行Autowired类Object

时间:2016-03-31 14:20:04

标签: java unit-testing mockito springmockito

我有下面的课程。在测试MyTestableClass时,我希望处理Autowired类。 我想在AutoWired类中仅模拟变量。

样本类如下 -

public class MyTestableClass {

    @Autowired
    private MyServiceClass service;

    public void handleError(){
    ...
    service.doSomething();

    }
}

public class MyServiceClass {

    @Autowired
    private JMSChannel channel;

    public void doSomething(){
        System.out.println("Inside Service class");
        .....
        channel.isAvailable();
        .....   
    }
}

@RunWith(MockitoJUnitRunner.class)
public class  MyTestableClassTest {
    private MyTestableClass  testClass= new MyTestableClass();

    private JMSChannel channel;

    @Before
    public void init(){
     channel= mock(JMSChannel.class);
     when(channel.isAvailable()).thenReturn(Boolean.TRUE);  
    }

    @Test
    public void test(){
        testClass.handleError();
    }
}

例如,控制台应该给我"内部服务类"在返回真实之前。

提前致谢!

1 个答案:

答案 0 :(得分:1)

您需要创建服务的实例和实例(或模拟它)并将其频道设置为模拟的频道,然后将MyTestableClass#service设置为此频道。类似的东西:

@Before
public void init(){
    channel= mock(JMSChannel.class);
    when(channel.isAvailable()).thenReturn(Boolean.TRUE); 
    MyServiceClass service = new MyServiceClass();
    ReflectionTestUtils.setField(service, "channel", channel);
    myTestableClass = new MyTestableClass();
    ReflectionTestUtils.setField(myTestableClass, "service", service);
}

来自spring-testReflectionTestUtils NB:您可以使用setter代替)