如何将 Mock 类从 src 移动到测试包并将它们作为 beans 加载

问题描述 投票:0回答:0

我被分配去升级一个项目,其中一项任务是将测试特定的模拟类移动到测试包中。我包含了你们可能会觉得对我有帮助的部分代码。我只是用junit学习。

这是主课

@SpringBootApplication
@ImportResource({ "classpath:applicationContext.xml" })
@EnableJpaRepositories(basePackages = "package.name", entityManagerFactoryRef = "firstFactory", transactionManagerRef = "firstTXManager")
@EnableIntegration
@EnableSwagger2
public class Driver {
    public static void main(String[] args) throws Exception {
        ...
        ...
        SpringApplication.run(Driver.class, args);
    }
    ...
    ...

    //I need to move the following code, but I don't know to where!
    @Bean
    @Profile({ "test" })
    public Mockers mockersTest() {
        return new Mockers();
    }

    @Bean
    @Profile({ "mock1", "mock2" })
    public MockersDev mockersDev() {
        return new MockersDev();
    }

    @Bean
    @Profile({ "online1", "online2", "online3", "staging" })
    public MockersProd mockersProd() {
        return new MockersProd();
    }
}

模拟服务器类。我尝试将这个模拟服务器和接下来的三个模拟类移动到测试包。但我不知道如何初始化它们,就像在主类中所做的那样。

import com.google.common.collect.Queues;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.text.MessageFormat;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelEvent;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelHandler;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.handler.codec.string.StringDecoder;
import org.jboss.netty.handler.codec.string.StringEncoder;
import org.jboss.netty.logging.InternalLoggerFactory;
import org.jboss.netty.logging.Slf4JLoggerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.util.Assert;

@ConditionalOnProperty(name = { "app.server.enabled" }, matchIfMissing = true)
@Configuration
public class MockServer {
    private final Logger log = LoggerFactory.getLogger(getClass());

    @Value("${tcp.mock.server.port}")
    private int port;

    private ServerBootstrap bootstrap;

    private ChannelGroup channels;

    @Autowired
    @Qualifier("mockServerQueue")
    private LinkedBlockingQueue<String> mockServerQueue;

    @Bean
    public LinkedBlockingQueue<String> mockServerQueue() {
    return Queues.newLinkedBlockingQueue(100);
    }

    @Bean
    public ApplicationListener<ContextRefreshedEvent> startServer() throws Exception {
        return new ApplicationListener<ContextRefreshedEvent>() {
            public void onApplicationEvent(ContextRefreshedEvent event) {
                InternalLoggerFactory.setDefaultFactory((InternalLoggerFactory) new Slf4JLoggerFactory());

        bootstrap = new ServerBootstrap((ChannelFactory) new NioServerSocketChannelFactory());

        bootstrap.setPipelineFactory(Channels.pipelineFactory(Channels
                .pipeline(new ChannelHandler[] { (ChannelHandler) new StringEncoder(StandardCharsets.UTF_8),
                        (ChannelHandler) new StringDecoder(StandardCharsets.UTF_8),
                        (ChannelHandler) new SimpleChannelHandler() {

                            public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
                                    throws Exception {
                                if (mockServerQueue.remainingCapacity() < 1) {
                                    mockServerQueue.clear();
                                }

                                Assert.isTrue(mockServerQueue.offer((String) e.getMessage(), 10L,
                                        TimeUnit.SECONDS), "failed to offer message");

                                ctx.getChannel().write(e.getMessage()).await(10L, TimeUnit.SECONDS);

                                ctx.sendUpstream((ChannelEvent) e);
                            }
                        } })));

        channels = (ChannelGroup) new DefaultChannelGroup();

        channels.add(bootstrap.bind(new InetSocketAddress(port)));

        log.info(MessageFormat.format("mock server started on port {0}", port));
            }
        }
    }

    @Bean
    public ApplicationListener<ContextClosedEvent> stopServer() throws Exception {
        return new ApplicationListener<ContextClosedEvent>() {
            public void onApplicationEvent(ContextClosedEvent event) {
                channels.close().awaitUninterruptibly(60L, TimeUnit.SECONDS);
    
                bootstrap.shutdown();
    
                log.info("mock server stopped");
            }
        };
    }
}

以下是三个Mock类

import de.svenjacobs.loremipsum.LoremIpsum;
import java.util.Calendar;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.transaction.annotation.Transactional;

@Transactional
public class Mockers
implements ApplicationListener<ContextRefreshedEvent>
{
    private LoremIpsum ipsum = new LoremIpsum();
    
    
    @Value("${tcp.mock.server.port}")
    private int port;
    ...
    ...    
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ...
        ...
    }
    ...//serveral other methods
    ...
}
import de.svenjacobs.loremipsum.LoremIpsum;
import java.util.Calendar;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.transaction.annotation.Transactional; // Added missing imports.
import org.springframework.context.ApplicationListener;
import au.com.streamlinemedia.abc.service.HttpService;

@Transactional
public class MockersDev implements ApplicationListener<ContextRefreshedEvent> {
    private LoremIpsum ipsum = new LoremIpsum();
    
    @Value("${tcp.mock.server.port}")
    private int port;
    ...
    ...
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ...
    }
    ...//serveral other methods
    ...
}
import de.svenjacobs.loremipsum.LoremIpsum;

import java.util.Calendar;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.transaction.annotation.Transactional;

@Transactional
public class MockersProd implements ApplicationListener<ContextRefreshedEvent> {
    private LoremIpsum ipsum = new LoremIpsum();
    
    @Value("${tcp.mock.server.port}")
    private int port;
    ...
    ...
    public void onApplicationEvent(ContextRefreshedEvent event) {
    //Empty method
    }
    ...//serveral other methods
    ...
}
java spring-boot mocking junit5
© www.soinside.com 2019 - 2023. All rights reserved.