在Spring集成上下文中,在mock bean中存根一个方法

时间:2015-03-13 01:06:50

标签: java spring mockito spring-integration

我正在尝试测试弹簧集成设置 我的单元测试如下,

@ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = { SIContext2Config.class })
public class FileMoverTest extends GenericTest {

@Test
public void testFileMover() throws InterruptedException {
    Thread.sleep(1000);
    int total = 2;
    int n = 0;
    for (int i = 1; i <= total; i++) {
        @SuppressWarnings("unchecked")
        Message<OfferMessage> msg = (Message<OfferMessage>) hdfsReadyChannel.receive(2000);
        System.out.println("Message # " + i + " received:" + msg.getPayload().getOfferFile().getAbsolutePath());
        n++;
    }
    Assert.state(n == total);
}

上下文类如下:

@Configuration
public class SIContext2Config { 

@Mock
private FsShell fsh;

@InjectMocks
@Mock
private MoveToHdfs fileMover;

@Bean
public Ingester ingester() {
    return new Ingester(fileMover);
}

@Mock
private Ingester ingester;

@Bean
public FilePickupHandler filePickupHandler() {
    return new FilePickupHandler();
}
}

现在,我正在努力做到这一点: Ingester bean有一个名为handle()的方法,MoveToHdfs对象fileMover在其中运行并调用move()。

public OfferMessage handle(Message<OfferMessage> msg) {
    // get hive directory path
    String remotePath = msg.getPayload().getOfferComponent().getHiveDirectory();
    String localFile = msg.getPayload().getOfferFile().getAbsolutePath();
    LOGGER.debug("Moving file {} to remote path:{}", localFile, remotePath);

    if (!fileMover.move(localFile, remotePath, true)) {
            throw new SomeException();
    }

    return msg.getPayload();
}

我只想让它返回真实。 但我无法弄清楚在哪里“存根”,或者如何存根。

1 个答案:

答案 0 :(得分:0)

为什么不将fileMover转发给@Bean

@Bean
public MoveToHdfs fileMover() {
    MoveToHdfs fileMover = Mockito.mock(MoveToHdfs.class);
    when(fileMover.move(anyString(), anyString(), anyBoolean())).thenReturn(true);
    return fileMover;
}