-2

I am writing JUnit test cases for my spring application. I use codepro tool in eclipse for generate test cases. when I run this test cases than it is run on JVM not on Tomcat server. so I want to know how it could be run on server? and which is best practice to run test cases on JVM or tomcat? and why? so please suggest me. code is as follow.

import java.io.InputStream;
import java.util.Properties;

import javax.servlet.http.HttpSession;

import junit.framework.TestCase;
import junit.framework.TestSuite;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.test.context.ContextConfiguration; 
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.bind.annotation.RequestMapping;

import com.zodiacapi.framework.business.ZodiacMobileBusinessTx;
import com.zodiacapi.framework.controller.ZodiacMobileAPIController;
import com.zodiacapi.framework.delegate.SendNotificationDelegate;
import com.zodiacapi.framework.dto.ReturnAPIMessageDTO;
import com.zodiacapi.framework.dto.UserDTO;
import com.zodiacweb.framework.cache.CacheService;
import com.zodiacweb.framework.cache.EhCacheServiceImpl;
import com.zodiacweb.framework.exception.ZodiacWebException;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:applicationContext.xml" })
public class ZodiacMobileAPIControllerTest extends TestCase {

private static final Logger logger =       LoggerFactory.getLogger(ZodiacMobileAPIControllerTest.class);

@Autowired
private ZodiacMobileBusinessTx zodiabMobileBusinessTx;

public ZodiacMobileBusinessTx getZodiabMobileBusinessTx() {
    return zodiabMobileBusinessTx;
}
@Test
public void testMobileLogin_1()
    throws Exception {
    ReturnAPIMessageDTO entities = new ReturnAPIMessageDTO();
    Properties prop = new Properties();
    InputStream in = getClass().getResourceAsStream("login.properties");
    prop.load(in);

    try{
    UserDTO result = zodiabMobileBusinessTx.login(prop.getProperty("username"), prop.getProperty("password"), prop.getProperty("apikey"), prop.getProperty("deviceid"), prop.getProperty("deviceModel"));


    System.out.println("result of test"+result);

} catch (ZodiacWebException e) {
    logger.error("Internal Server Error fetching user info", e);
    entities.setStatus("false");
    entities.setMessage(e.getMessage());
    entities.setVersion("");

} catch (Throwable t) {

    entities.setStatus("false");
    entities.setMessage(t.getMessage());
    entities.setVersion("");
}

}

}

2 Answers2

0

For a unit test you would usually execute it within the JVM. You would probably only execute Integration/Functional tests on an application running in a server.

The choices you have for testing a Spring Controller(That I am familiar with) are:

  1. Test the controller as a regular POJO outside of the container and server for example : MyController controller = new MyController())
  2. Test the controller using Spring Test MVC. This will actually start up Spring during your tests.(I prefer this option) see Unit Test Spring Controllers for some examples.
  3. If you want to test your application in a real tomcat instance you can use Arquillian together with The Arquillian Spring Extension. This last option is definitely the most complex in terms of learning curve. But it's nice to be aware of.(Haven't successfully used it with a Spring Application myself)
  • My test class is controller of my application. Would you need to see code? – Shrupal Jobanputra Dec 29 '15 at 08:52
  • Yes, because it is possible to test Spring Controllers both inside and outside of tomcat. – Duran Wesley Harris Dec 30 '15 at 05:12
  • I have edited my post to try outline the options that you have available to test Spring Controllers. – Duran Wesley Harris Dec 30 '15 at 05:27
  • I had try for @RunWith(Arquillian.class) instead of @RunWith(SpringJUnit4ClassRunner.class) But i think jar file for it is missing in build path that's why it throws the error for me. so if you know which jar file is used than please suggest me. – Shrupal Jobanputra Dec 30 '15 at 12:24
  • Logback allows you to use variables in the config file like so: ${USER_HOME}/myApp.log Does this help? – Duran Wesley Harris Jan 05 '16 at 08:38
  • yes it's working.. and I had also try for logback-test.xml as you told me. – Shrupal Jobanputra Jan 06 '16 at 03:38
  • Excellent! It's easy once you get comfortable with it – Duran Wesley Harris Jan 06 '16 at 05:57
  • Yes..Do you have any idea about how to automatically build Junit test cases by using jenkins rather than using apache ant? – Shrupal Jobanputra Jan 06 '16 at 10:33
  • You will need to have jenkins invoke your ant build which will in turn run your tests... I dont think it is possible to run a Jenkins build without the use of either Ant or Maven. You should be able to set up the Jenkins job to build your project with your existing ant build.xml...this way Jenkins will execute your ant unit test target before building – Duran Wesley Harris Jan 06 '16 at 11:28
  • see (http://stackoverflow.com/questions/16669507/run-junit-tests-automatically-in-jenkins-without-maven-or-ant) It tells the use @RunWith(ClasspathSuite.class) for use Jenkins without maven and ant. but i can not able to understand what it is. but what you are suggest is use ant and build it in Jnkins right? – Shrupal Jobanputra Jan 06 '16 at 13:01
0

Don't worry about using Arquillian for now ... it takes some time to learn.

See my code below for a working example of testing a spring controller. I noticed from your code sample that you did not have all the correct annotations and the initialization method.

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = App.class)
@TestPropertySource(locations = "classpath:test.properties")
@WebAppConfiguration
public class AdminUserControllerUnitTest {

MockMvc mvc;

@Autowired
WebApplicationContext webApplicationContext;



@Before
public void initialize(){

    mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}


@Test
public void testListUsers() throws Exception {

    Account account = new Account();
    account.setId(1l);

    mvc.perform(
                get("/admin/user")
                        .sessionAttr("account",account)                     
               );
                .andExpect(MockMvcResultMatchers.model().attribute("users",hasSize(4)));


}
  • No I think it uses some sort of mock servlet container. Why do you want to test it in tomcat specifically? If you need to go that route then look at https://codewithzenmind.wordpress.com/2013/09/20/spring-mvc-based-application-test-driven-development-part-6-product-search-form-integration-test-with-tomcat-7-maven-plugin/ – Duran Wesley Harris Dec 31 '15 at 05:01
  • I want to run it in server because of i want separate logs for Junit test cases and application logs. I am using logback.xml for it. and in logback.xml I use "catalina.home" server variables for give log file path. now when I run test cases it will not find those server variables because it's not run in server. If you have any other way to create separate logs for both than please suggest me. should I keep two logback.xml file in single project for both? or in one file I can configure it? – Shrupal Jobanputra Dec 31 '15 at 06:05
  • Can't you create an additional logback.xml in /scr/test/resources that your tests will use? Then you can provide a different path to the logfile in /src/test/resources/logback.xml – Duran Wesley Harris Dec 31 '15 at 06:25
  • write now it takes logback.xml from class path by default so where should i configure path for logback.xml in my project? I mean in applicationContext.xml or web.xml or any other? how application will comes to know which logback.xml file will be read while running test cases and which while running application? – Shrupal Jobanputra Dec 31 '15 at 06:33
  • Ok it seems you actually need to rename it to logback-test.xml. see http://logback.qos.ch/manual/configuration.html – Duran Wesley Harris Dec 31 '15 at 07:01
  • logback-test.xml is for maven only.. because Maven will ensure that it won't be included in the artifact produced. so we can use it during testing. As it also written in above link which you send. But if I use it in my simple application than it's not working. Is it possible with non maven application? – Shrupal Jobanputra Dec 31 '15 at 13:01