用jUnit测试controller、Service

1.测试controller部分代码如下:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = { "classpath:resources/applicationContext.xml", "classpath:resources/springmvc-servlet.xml" })
public class CommentControllerTest {
	@Autowired
	private CommentController commentController;//引入要测试的controller
	
	private MockMvc mockMvc;

	@Before
	public void setup() {
		mockMvc = MockMvcBuilders.standaloneSetup(commentController).build();
	}

	@Test
	@Rollback(false) //插入需要此注解,不然插不进数据库
	public void addCommnet(){
		String result = "" ;
		try {
			ResultActions ra = this.mockMvc.perform(MockMvcRequestBuilders.post("/comment/addComment")
					.param("startlevel", "5").param("commentcontent", "环境很好").param("shopid", "9562ed5d02b348d1bfec1699ba1df36b")
					.param("commentuserid", "d07136c725754cd7827a35581d4a4456").param("consumption", "20.5")
					.param("url", "comment/images")
					.param("palate", "4").param("environment", "4").param("service", "4")
					//.param("key", "[{id:'',imagename:'a1',imageupdatename:'',url:'a1',commentid:'',createdate:''},{id:'',imagename:'a2',imageupdatename:'',url:'a2',commentid:'',createdate:''}]")//前台应出入json格式
					.param("imagename", "袋鼠,兔子")//前台传入逗号分割的字符串
					.param("recommends", "蛋炒西红柿,橙汁")
					);
			MvcResult mr = ra.andReturn();
			result = mr.getResponse().getContentAsString();
			System.out.println("+++++++++++"+result);
		} catch (Exception e) {
			Assert.fail("fail");
			e.printStackTrace();
		}
		
	}
	
}
2.jUnit测试Service:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = { "classpath:resources/applicationContext.xml" })
public class Share_Test {
	
	@Autowired
	private ShareService shareService;//分享Service
	
	/**
	 * 添加分享
	 */
	@Test
	public void addShare(){
		Share share = new Share();
		share.setId(UUIDUtil.generateKey());
		share.setUserid(UUIDUtil.generateKey());
		share.setShopid(UUIDUtil.generateKey());
		share.setShareaddress("www.baidu.com");
		try {
			shareService.insertShare(share);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 删除分享
	 */
	@Test
	public void deleteShare(){
		String id = "109ece2bb310440494150cac78184c93";
		try {
			shareService.deleteShareByPrimaryKey(id);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 查询分享
	 */
	@Test
	public void selectShare(){
		List s = shareService.selectShare();
		for (Share share : s) {
			System.out.println("++++++++++++++++++++++++"+share.getShareaddress());
		}
	}
	
	



你可能感兴趣的:(jUnit)