编写junit测试用例的正确方法

时间:2018-08-25 18:50:17

标签: junit mockito powermockito

我是编写Junit测试用例的初学者。 我上课

package com.xyz.fdp.business.tibco.producer;
import java.util.List;
import java.util.Properties;
import java.util.UUID;

import javax.annotation.PostConstruct;
import javax.ejb.DependsOn;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.inject.Inject;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.xyz.fdp.business.tibco.utils.TibcoConstant;
import com.xyz.fdp.core.dsm.framework.service.impl.FDPMetaCacheProducer;
import com.xyz.fdp.dao.dto.FDPTibcoConfigDTO;
import com.xyz.fdp.dao.fdpadmin.FDPTibcoConfigDAO;

@Singleton(name = "TibcoJMSQueueProducer")
@DependsOn(value = { "PropertyUtils", "ApplicationConfigCache" })
@Startup
public class TibcoJMSQueueProducer {

    private static final Logger LOGGER = LoggerFactory.getLogger(FDPMetaCacheProducer.class);

    private static QueueConnectionFactory factory;
    private QueueConnection connection;
    private QueueSession session;


    private FDPTibcoConfigDAO fdpTibcoConfigDao;

    private String providerURL;

    private String userName;
    private String password;



    @Inject
    void setTibcoconfigDAO( FDPTibcoConfigDAO fdpTibcoConfigDao){
        this.fdpTibcoConfigDao = fdpTibcoConfigDao;
    }

    void setQueueConnection(QueueConnection connection){
        this.connection = connection;
    }

    void setQueueSession(QueueSession session){
        this.session = session;
    }


    static void setQueueConnectionFactory(QueueConnectionFactory connectionFactory){
        factory = connectionFactory;
    }


    @PostConstruct
    public void constructProducer(){
        configure();
    }

    private void configure() {
        List<FDPTibcoConfigDTO> tibcoConfigList = fdpTibcoConfigDao.getAllTibcoConfig();
        if(!tibcoConfigList.isEmpty()){
            FDPTibcoConfigDTO fdpTibcoConfigDTO = tibcoConfigList.get(tibcoConfigList.size()-1);
            String providerURL = getProviderUrl(fdpTibcoConfigDTO);

            setProviderUrl(providerURL);
            String userName = fdpTibcoConfigDTO.getUserName();
            String password = fdpTibcoConfigDTO.getPassword();
            this.userName = userName;
            this.password=password;
            factory = new com.tibco.tibjms.TibjmsQueueConnectionFactory(providerURL);


        }
    }

    private void setProviderUrl(String providerURL) {
        this.providerURL = providerURL;
    }

    private String getProviderUrl(final FDPTibcoConfigDTO FDPTibcoConfigDTO) {
        return TibcoConstant.TCP_PROTOCOL + FDPTibcoConfigDTO.getIpAddress().getValue() + TibcoConstant.COLON_SEPERATOR + FDPTibcoConfigDTO.getPort();
    }

    private Object lookupQueue(String queueName) throws JMSException {

        Properties props = new Properties();
        Object tibcoQueue = null;
        props.setProperty(Context.INITIAL_CONTEXT_FACTORY, TibcoConstant.TIB_JMS_INITIAL_CONTEXT_FACTORY);
        props.setProperty(Context.PROVIDER_URL, this.providerURL);
        props.setProperty(TibcoConstant.TIBCO_CONNECT_ATTEMPT, "20,10");
        props.setProperty(TibcoConstant.TIBCO_RECOVER_START_UP_ERROR, "true");
        props.setProperty(TibcoConstant.TIBCO_RECOVER_RECONNECT_ATTEMPT, "20,10");

        try {
            InitialContext context = getInitialContext(props);
            tibcoQueue = context.lookup(queueName);
            if(tibcoQueue == null){
                throw new JMSException("Invalid Queue Name: [ " +queueName +" ]");
            }
        } catch (NamingException e) {
            LOGGER.error("Queue not available on server [ " +queueName +" ]",e);
            throw new JMSException("Invalid Queue Name: [ " +queueName +" ]");
        }

        return tibcoQueue;
    }

    InitialContext getInitialContext(Properties props) throws NamingException {
        return new InitialContext(props);
    }

    public void pushIntoQueueAsync(String message,String queueName) throws JMSException {
        connection = factory.createQueueConnection(userName, password);
        connection.start();
        session = connection.createQueueSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
        Queue pushingQueue = (Queue)lookupQueue(queueName);
        QueueSender queueSender = session.createSender(pushingQueue);
        queueSender.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        TextMessage sendXMLRequest = session.createTextMessage(message);
        queueSender.send(sendXMLRequest);
        LOGGER.info("Pushing Queue {0} ,Pushing Message : {1}", pushingQueue.getQueueName(), sendXMLRequest.getText());
    }

    public String pushIntoQueueSync(String message,String queueName,String replyQueueName) throws JMSException {
        connection = factory.createQueueConnection(userName, password);
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination destination = (Destination)lookupQueue(queueName);
        MessageProducer messageProducer = session.createProducer(destination);

        session = connection.createQueueSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
        UUID randomUUID =UUID.randomUUID();
       TextMessage textMessage = session.createTextMessage(message);
       String correlationId = randomUUID.toString();
       //Create Reply To Queue
       Destination replyDestination = (Destination)lookupQueue(queueName);
       textMessage.setJMSReplyTo(replyDestination);
       textMessage.setJMSCorrelationID(correlationId);
       String messgeSelector = "JMSCorrelationID = '" + correlationId + "'";

       MessageConsumer replyConsumer = session.createConsumer(replyDestination,messgeSelector);
       messageProducer.send(textMessage, javax.jms.DeliveryMode.PERSISTENT,   javax.jms.Message.DEFAULT_PRIORITY, 1800000);

       Message replayMessage = replyConsumer.receive();

       TextMessage replyTextMessage = (TextMessage) replayMessage;
       String replyText = replyTextMessage.getText();
       LOGGER.info("Pushing Queue {0} ,Pushing Message : {1}", queueName, message);
        return replyText;
    }

    public static QueueConnectionFactory getConnectionFactory(){
        return factory;
    }


}

我写了如下的Junit测试用例

package com.xyz.fdp.business.tibco.producer;

import static org.junit.Assert.assertNull;

import java.util.Collections;
import java.util.List;
import java.util.Properties;

import javax.jms.JMSException;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.TextMessage;
import javax.naming.InitialContext;

import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.modules.junit4.PowerMockRunner;

import com.xyz.fdp.dao.dto.FDPCodeTypeDTO;
import com.xyz.fdp.dao.dto.FDPTibcoConfigDTO;
import com.xyz.fdp.dao.fdpadmin.FDPTibcoConfigDAO;
import com.tibco.tibjms.TibjmsQueueConnectionFactory;

import junit.framework.Assert;

    @RunWith(PowerMockRunner.class)
    public class TibcoJMSQueueProducerTest {

    private static final String inMessage = "requestBody";
    private static final String outMessage = "responseBody";
    private static final String queueName = "changeRatePlanQueue";
    private static final String replyQueueName = "changeRateReplyPlanQueue";

    private TibcoJMSQueueProducer queueProducer;
    @Mock
    private FDPTibcoConfigDAO fdpTibcoConfigDao;


    @Mock
    private TibjmsQueueConnectionFactory connectionFactory;

    @Mock
    private QueueConnection connection;

    @Mock
    private QueueSession session;

    @Mock 
    private InitialContext context;

    private Queue pushingQueue;
    @Mock
    private QueueSender queueSender;

    @Mock
    private TextMessage sendXMLRequest;

    @Mock
    private List<FDPTibcoConfigDTO> tibcoConfigList;

    @Before
    public void setup() throws JMSException{
        queueProducer = Mockito.spy(TibcoJMSQueueProducer.class);

        queueProducer.setQueueSession(session);
        queueProducer.setQueueConnection(connection);
        queueProducer.setTibcoconfigDAO(fdpTibcoConfigDao);

        FDPTibcoConfigDTO tibcoConfigDTO = new FDPTibcoConfigDTO();
        tibcoConfigDTO.setPort(9999);
        tibcoConfigDTO.setUserName("Admin");
        tibcoConfigDTO.setPassword("123456789");
        FDPCodeTypeDTO ipAddress = new FDPCodeTypeDTO();
        tibcoConfigDTO.setIpAddress(ipAddress);
        ipAddress.setValue("127.0.0.1");
        Mockito.when(fdpTibcoConfigDao.getAllTibcoConfig()).thenReturn(Collections.singletonList(tibcoConfigDTO));
        pushingQueue = new Queue() {
            @Override
            public String getQueueName() throws JMSException {
                return queueName;
            }
        }; 
        Mockito.when(sendXMLRequest.getText()).thenReturn(inMessage);


    }


    @Test
    public void constructProducerTest_empty_config() throws Exception{
        Mockito.when(fdpTibcoConfigDao.getAllTibcoConfig()).thenReturn(Collections.<FDPTibcoConfigDTO>emptyList());
        queueProducer.constructProducer();
        Assert.assertEquals(null, TibcoJMSQueueProducer.getConnectionFactory());
    }



    @Test(expected=JMSException.class)
    public void constructProducerTest_nonempty_config_null_lookup() throws Exception{
        queueProducer.constructProducer();
        TibcoJMSQueueProducer.setQueueConnectionFactory(connectionFactory);// Only for Testing purpose
        Mockito.when(connectionFactory.createQueueConnection(Mockito.anyString(), Mockito.anyString())).thenReturn(connection);
    /*  PowerMockito.when(queueProducer.getInitialContext(Mockito.any(Properties.class))).thenReturn(context);*/
        PowerMockito.doReturn(context).when(queueProducer).getInitialContext(Mockito.any(Properties.class));
        PowerMockito.when(context.lookup(Mockito.anyString())).thenReturn(null);

        queueProducer.pushIntoQueueAsync(inMessage, queueName);
        TibcoJMSQueueProducer.setQueueConnectionFactory(null);

    }


    @Test
    public void constructProducerTest_nonempty_config_with_notnull_lookup() throws Exception{
        queueProducer.constructProducer();
        TibcoJMSQueueProducer.setQueueConnectionFactory(connectionFactory);// Only for Testing purpose
        Mockito.when(connectionFactory.createQueueConnection(Mockito.anyString(), Mockito.anyString())).thenReturn(connection);
        Mockito.when(connection.createQueueSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE)).thenReturn(session);
        Mockito.when(session.createSender(pushingQueue)).thenReturn(queueSender);
        PowerMockito.doReturn(context).when(queueProducer).getInitialContext(Mockito.any(Properties.class));
        PowerMockito.when(context.lookup(Mockito.anyString())).thenReturn(pushingQueue);
        Mockito.when(session.createTextMessage(Mockito.anyString())).thenReturn(sendXMLRequest);


        queueProducer.pushIntoQueueAsync(inMessage, queueName);
        TibcoJMSQueueProducer.setQueueConnectionFactory(null);
        Mockito.verify(queueSender).send(sendXMLRequest);

    }
}

我的第一个测试方法是@Test

public void constructProducerTest_empty_config() throws Exception{
        Mockito.when(fdpTibcoConfigDao.getAllTibcoConfig()).thenReturn(Collections.<FDPTibcoConfigDTO>emptyList());
        //when(tibcoConfigList.isEmpty())
        //queueProducer.constructProducer();

        //Assert.assertEquals(null, TibcoJMSQueueProducer.getConnectionFactory());
        queueProducer.constructProducer();
    }

我的一位同事告诉我。这是编写Junit测试方法的错误方法。 Junit测试方法应独立。因为我使用过getConnectionFactory()方法。但是,如果您查看constructProducer()方法。这是空方法。因此我创建了一个测试用例,以检查如果没有从dao层获得的配置列表,工厂应该为空。因此,我需要检查factory是否真的为空。所以我必须创建静态方法,因为工厂实例是静态的。

在编写Junit测试用例时,我几乎不知道应该怎么看。

如果有人可以根据以下课程讲解,那么我们可以在下面创建哪些可能的测试用例会更好。

0 个答案:

没有答案