2

我有一个 resful 并希望同时使用 JUnit 和一个 HTML 页面进行测试 在 HTML 页面中,我没有问题,当我从 JUnit 发送数据时 resful 总是收到 null

这是 RESTFUL :

@Component
@Path("/dao")
public class RestServiceControllerImp implements RestServiceController
{
    @POST
    @Path("/test/")
    @Consumes({
                MediaType.APPLICATION_FORM_URLENCODED
                ,MediaType.MULTIPART_FORM_DATA
                ,MediaType.TEXT_HTML
                ,MediaType.TEXT_PLAIN
                ,MediaType.TEXT_XML
    })  
            public Response getMessage( 
                    @FormParam("dataInput") String dataInput
                   )
    {
        log.info("Message from getProductByID WS");
        log.info("Valeur reçu en entrée :"+ServiceConstants.RETOUR_CHARIOT+dataInput);
        if (dataInput == null)
        {
            result = "your value is null";
        }
        else
        {
            result = "your value :"+dataInput;
        }

        return Response.status(201).entity(result).build();
    }
}

这是html页面:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>test</title>
</head>
<body>
    <form action="http://localhost:8080/MyRestful/dao/test" method="POST" >
        <textarea name="dataInput" rows="8" cols="50">
            Hello World
        </textarea> 
        <p>
        <input type ="submit" value="Send"/>
        </p>
    </form>
</body>
</html>

这是我从这个页面运行时的日志

[http-bio-8080-exec-2] INFO com.myresful.rest.controller.RestServiceControllerImp - Message from getProductByID WS
[http-bio-8080-exec-2] INFO com.myresful.rest.controller.RestServiceControllerImp - Valeur reçu en entrée :
            Hello World 

这是我的junit测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext_Test.xml")
// @ContextConfiguration("classpath:applicationContext.xml")
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class TestUnitRest 
{
    @Autowired
    private BoxControlUnitDao objBoxControlUnitDao;
    private Logger log = LoggerFactory.getLogger(TestUnitRest.class);
    private String userName ;
    private String userPwd ;
    private String urlToConnect ;
    private String responseMsg = "";
    private String dataInput;
    @Test
    public void test01GetMessageFromRestful() throws Exception 
    {
        log.info("*****************************test01GetMessageFromRestful******************");
        userName = "nizar";
        userPwd = "nizar123";


        log.info("*****************************Génération de l'url******************");
        urlToConnect = "http://localhost:8080/MyRestful/dao/test";
        log.info("Url appelé : "+urlToConnect);
        AutenticateFactory objAutenticateFactory = new AutenticateFactory(urlToConnect, userName, userPwd);

        dataInput ="Hello World";

        responseMsg = objAutenticateFactory.putMessage(dataInput);

        log.info("Réception du retour :"+"\n"+responseMsg);


        if (responseMsg.startsWith("your value is null")) 
        {
            fail(
                    "L'appel du : "+urlToConnect +" à renvoyé :"+
                    "\n"+
                    responseMsg
                    );
        } 
        else 
        {
            log.info(
                    "Réponse reçu OK" + 
                    "\n"+ 
                    "-----contenu de la réponse------" + 
                    "\n" + 
                    responseMsg+ 
                    "\n" + 
                    "-----fin------"
                    );
        }
    }
}

这是我运行 junit 测试时来自 resful 的日志

[http-bio-8080-exec-6] INFO com.MyResful.rest.controller.RestServiceControllerImp - Message from getProductByID WS
[http-bio-8080-exec-6] INFO com.MyResful.rest.controller.RestServiceControllerImp - Valeur reçu en entrée :
null

Junit 控制台

java.lang.AssertionError: L'appel du : http://<server>/MyResful/dao/test à renvoyé :
your value is null
    at org.junit.Assert.fail(Assert.java:88)

我使用 REALM tomcat7 和这个类来验证

public class AutenticateFactory 
{
    static Logger log = LoggerFactory.getLogger(AutenticateFactory.class);
    String urlToConnect;
    String userName;
    String userPwd;
    String msgResponse;
    int statusResponse;
    private com.sun.jersey.api.client.WebResource webResource;
    private com.sun.jersey.api.client.Client client;

    public AutenticateFactory(String urlToConnect, String userName,String userPwd) 
    {
        super();
        this.urlToConnect = urlToConnect;
        this.userName = userName;
        this.userPwd = userPwd;
        com.sun.jersey.api.client.config.ClientConfig config = new com.sun.jersey.api.client.config.DefaultClientConfig();
//        Déclaration du client
        client = com.sun.jersey.api.client.Client.create(config);
        client.addFilter(new LoggingFilter());
        client.addFilter(new com.sun.jersey.api.client.filter.HTTPBasicAuthFilter(userName, userPwd));
//        Déclaration du web ressource
        webResource = client.resource(urlToConnect);
    }

    public String getUrlToConnect() {
        return urlToConnect;
    }

    public void setUrlToConnect(String urlToConnect) {
        this.urlToConnect = urlToConnect;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserPwd() {
        return userPwd;
    }

    public void setUserPwd(String userPwd) {
        this.userPwd = userPwd;
    }

    public String getMessage() throws Exception 
    {
        try
        {
            ClientResponse response = webResource.type(javax.ws.rs.core.MediaType.TEXT_HTML).get(ClientResponse.class);
            statusResponse = response.getStatus();
            msgResponse = response.getEntity(String.class);
//          Vérifier le retour de la requete
            if (statusResponse != HttpURLConnection.HTTP_OK)
            {
                throw (new Exception(
                                    ServiceConstants.HTTP_ERR_CODE+ statusResponse + 
                                    ServiceConstants.RETOUR_CHARIOT+ msgResponse
                                    ));
            }
        }
        catch (Exception err)
        {
            msgResponse = ServiceConstants.HTTP_ERR_CODE+ statusResponse + 
                          ServiceConstants.RETOUR_CHARIOT+ err.getMessage();

        }
        client.destroy();
        return msgResponse ;            
    }

    public String putMessage(String inputValue)  throws Exception
    {
        try
        {

            ClientResponse response = webResource.type(javax.ws.rs.core.MediaType.TEXT_HTML).post(ClientResponse.class, inputValue);
            statusResponse = response.getStatus();
            msgResponse = response.getEntity(String.class);
//          Vérifier le retour de la requete
            if (statusResponse != HttpURLConnection.HTTP_CREATED)
            {
                throw (new Exception(
                                    ServiceConstants.HTTP_ERR_CODE+ statusResponse + 
                                    ServiceConstants.RETOUR_CHARIOT+ msgResponse
                                    ));
            }
        }
        catch (Exception err)
        {
            /*msgResponse = ServiceConstants.HTTP_ERR_CODE+ statusResponse + 
                          ServiceConstants.RETOUR_CHARIOT+ err.getMessage();*/

            msgResponse = err.getMessage();
        }
        client.destroy();
        return msgResponse ;
    }
}

为什么我在运行 junit 测试时收到null

4

1 回答 1

0

我在 junit 测试中找到了答案 1/ 我添加了一个 com.sun.jersey.api.representation.Form,在我像这样将一些数据注入这个表单之后

        String dataInput = "Hello World"
Form objForm = new Form();
objForm.add("dataInput", dataInput);

2/ 在我的身份验证类中,我添加了一个像这样的 Form 的新方法

    public String putForm(Form objForm)  throws Exception
    {
        try
        {

            ClientResponse response = webResource.type(javax.ws.rs.core.MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class, objForm);
            statusResponse = response.getStatus();
            msgResponse = response.getEntity(String.class);
//          Vérifier le retour de la requete
            if (statusResponse != HttpURLConnection.HTTP_CREATED)
            {
                throw (new Exception(
                                    ServiceConstants.HTTP_ERR_CODE+ statusResponse + 
                                    ServiceConstants.RETOUR_CHARIOT+ msgResponse
                                    ));
            }
        }
        catch (Exception err)
        {
            /*msgResponse = ServiceConstants.HTTP_ERR_CODE+ statusResponse + 
                          ServiceConstants.RETOUR_CHARIOT+ err.getMessage();*/

            msgResponse = err.getMessage();
        }
        client.destroy();
        return msgResponse ;
    }

3/我回到我的junit测试类并添加

responseMsg = objAutenticateFactory.putForm(objForm);

我从中找到了Form的解决方案

于 2013-06-04T14:16:09.600 回答