本次测试使用的是springboot 中的测试
1.(对service 的测试)下面的测试。将会启动容器进行测试
@RunWith(SpringRunner.class) @SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT) // 随机端口 public class MyTest { @Autowired EquipmentFaultService service; @Test public void mytest(){ EquipmentFaultModel equipmentFaultById = service.getEquipmentFaultById("619d79f2-6c77-42a3-b0e9-49c5ebf2fdef"); Assert.assertNotNull(equipmentFaultById); } }
2. controller 的测试
package com.hollysys.smartfactory.account; import com.hollysys.smartfactory.account.system.model.vm.EquipmentFaultModel; import com.hollysys.smartfactory.account.system.service.EquipmentFaultService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import static org.mockito.BDDMockito.given; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** * Description: * * @author cy * @date 2019年06月12日 18:32 * Version 1.0 */ @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc public class MyTest { @Autowired private MockMvc mvc; @MockBean EquipmentFaultService service; @Test public void mytest() throws Exception { // EquipmentFaultModel equipmentFaultById = service.getEquipmentFaultById("619d79f2-6c77-42a3-b0e9-49c5ebf2fdef"); EquipmentFaultModel equipmentFaultModel = new EquipmentFaultModel(); equipmentFaultModel.setAttdataPkid("1qqq"); given(this.service.getEquipmentFaultById("sboot")) .willReturn(equipmentFaultModel); MvcResult mvcResult = this.mvc.perform(get("/equipment_fault/dda0ddf0-acff-4649-a17d-2544b316b408")).andDo(print()) .andExpect(status().isOk()).andReturn(); System.out.println("结果:"+mvcResult.getResponse().getContentType()); } }
3. service 测试
@RunWith(SpringRunner.class) @SpringBootTest @Transactional // 添加事务之后,单元测试就会产生回滚 public class MyTest { @Autowired EquipmentFaultService service; @Test public void mytest() { // EquipmentFaultModel equipmentFaultById = service.getEquipmentFaultById("619d79f2-6c77-42a3-b0e9-49c5ebf2fdef"); EquipmentFaultModel equipmentFaultById = service.getEquipmentFaultById("619d79f2-6c77-42a3-b0e9-49c5ebf2fdef"); equipmentFaultById.setFaultType("1"); String s = service.updateEquipmentFault(equipmentFaultById); Assert.assertEquals(s,"619d79f2-6c77-42a3-b0e9-49c5ebf2fdef"); } }