java的Spring学习2- junit和mock
<!-- 引用Mock --> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>1.9.0</version> <scope>test</scope> </dependency>
package com.xxx.test.subscribe; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.springframework.http.HttpEntity; import org.springframework.web.client.RestTemplate; import java.util.HashMap; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.MockitoAnnotations.initMocks; import static org.mockito.Matchers.anyObject; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; public class SubscribeTest { private SubscribeEventRequest request; @InjectMocks private SubscribeEventPushImpl service; @Mock private RestTemplate restTemplate; @Mock private PushProperties pushProperties; @Before public void setUp() throws Exception { initMocks(this); HashMap<String, String> keys = new HashMap<String, String>(); request = new SubscribeEventRequest(); request.setKeys(keys); request.setPublishTime(System.currentTimeMillis()); request.setPublishType(PublishTypes.Push.getCode()); request.setSubscribeType(401); } @Test public void testUrl() { this.mockResources(); SubscribeReq req = new SubscribeReq(request); req.setPhoneNumber("18688888888"); req.setDeviceId("234523452345ab"); req.setOs(1); SubscribeResp resp = service.subscribe(req); Assert.assertEquals(resp.getCode(), 0); } private void mockResources() { when(pushProperties.getAppKey()).thenReturn(SubscribeConsts.PUSH_DEFAULT_APPKEY); when(pushProperties.getSource()).thenReturn(SubscribeConsts.PUSH_DEFAULT_SOURCE); when(pushProperties.getPushTaskUrl()).thenReturn(""); String jsonResult = "{\n" + " \"code\" : 0,\n" + " \"payload\" : {\n" + " \"act\" : 0\n" + " }\n" + "}"; when(restTemplate.postForObject(anyString(), anyObject(), eq(String.class))).thenReturn (jsonResult); } }