利用Spring 提供的测试框架,对controller层进行集成测试。之前针对controller层的测试,采用的是mock(mockito)service层的方法。
由于开发历史原因,controller层并没有在配置文件中进行bean配置,所以在此处,使用手工创建controller对象,并导入service层。但如果配置好了,直接Autowired就行。不然的话,会报空指针错误。
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpMethod;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:CenterApplicationContext.xml"})
@TransactionConfiguration(
transactionManager = "txManager", defaultRollback=true)
public class AccountAPIControllerTest extends AbstractTransactionalJUnit4SpringContextTests{
@Autowired
private ApplicationContext ctx;
@Autowired
private AccountDao accountDao;
@Autowired
private ChargeRecordDao chargeRecordDao;
private AccountAPI accountAPI;
private static MockHttpServletRequest request;
private static MockHttpServletResponse response;
private ReturnMsg reMsg;
@Before
public void setUp() throws Exception {
accountAPI = new AccountAPI();
accountAPI.setAccountService((AccountService)ctx.getBean("accountService"));
request = new MockHttpServletRequest();
request.setCharacterEncoding("UTF-8");
response = new MockHttpServletResponse();
reMsg = new ReturnMsg();
}
//事物回滚
@Test
public void testAsyncUpdate() throws Exception {
request.setRequestURI("/account/asyncupdate");
request.setMethod(HttpMethod.POST.name());
String content = "{\"trans_id\":\"123456789qwertyuikxnchgfbtu23ytd\",\"code\":\"SHANGXUN-CPC\",\"clientID\":\"1453811830\",\"point\":\"1.1234\",\"categoryId\":\"1521\",\"orgType\":\"0\"}";
reMsg = accountAPI.asyncUpdate(request, response, content);
//更新账户成功
assertEquals(AccountAPIResponseType.SUCCESS.getValue(), reMsg.getCode());
assertEquals("", reMsg.getErrorMsg());
//返回状态码200
assertEquals(response.getStatus(), 200);
//查询账户数据库,相应记录不为空
assertNotNull(accountDao.getById("1453811830_SHANGXUN-CPC"));
//查询充值表,相应记录不为空
assertNotNull(chargeRecordDao.getById("123456789qwertyuikxnchgfbtu23ytd"));
}
}