Mock注入依赖记录

在使用mock进行接口测试时,一般要做三件事情,即打桩,注入和调桩

  • 打桩:创建mock桩,指定API请求内容及其映射的mock响应内容
  • 注入:将创建的mock注入到被测服务中
  • 调桩:被测服务来请求mock桩并接收mock响应

XialuService依赖了UserService和OrderService,测试validateUserEmail时,UserService可能还在开发中又或者需要进行一些极端测试依赖的服务不太好返回响应的测试数据,这时就可以使用mock,模拟真实的UserService,打桩设置测试数据,并注入到XialuService中,再进行测试。


mock服务依赖.png

方法一:

通过反射注入

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {XialuApplication.class})
public class ValidateEmailTest {

    @Autowired
    @InjectMocks
    private XialuService xialuService;
    @Mock
    private UserService userService;

    @Before
    public void setup() {

        User user = new User();
        user.setAge(13);
        user.setName("xialu");
        MockitoAnnotations.initMocks(this);
        /**
          * 使用@Mock注解失效的话,可以选择手动使用反射注入userService服务到autoApplyService服务中.
          *
          */
        ReflectionTestUtils.setField(autoApplyService, "userService", userService); 

        Mockito.when(userService.getUserById("001")).thenReturn(user);
    }

    /**
     * 校验用户邮箱是否存在.
     */
    @Test
    public void testValidateUserEmailIsEmpty() {

        xialuService.validateUserEmail(userId);
    }
}

方法二:

使用MockBean

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {XialuApplication.class})
public class ValidateEmailTest {

    @Autowired
    private XialuService xialuService;
    @MockBean
    private UserService userService;

    @Before
    public void setup() {
        Mockito.when(userService.getUserById("001")).thenReturn(user);
    }

    /**
     * 校验用户邮箱是否存在.
     */
    @Test
    public void testValidateUserEmailIsEmpty() {

        xialuService.validateUserEmail(userId);
    }
}

方法三:

在XialuService中创建一个setUserService的方法.

public class XialuService {

@Autowired
private UserService userService;
@Autowired
private OrderService orderService;

   public void setUserService(UserService userService) {
           this.userService = userService;
   }

   public void validateUserEmail(String userId) {
        // ......
   }
}

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {XialuApplication.class})
public class ValidateEmailTest {

    @Autowired
    @InjectMocks
    private XialuService xialuService;
    @Mock
    private UserService userService;

    @Before
    public void setup() {

        User user = new User();
        user.setAge(13);
        user.setName("xialu");
        MockitoAnnotations.initMocks(this);

        Mockito.when(userService.getUserById("001")).thenReturn(user);
    }

    /**
     * 校验用户邮箱是否存在.
     */
    @Test
    public void testValidateUserEmailIsEmpty() {

        xialuService.validateUserEmail(userId);
    }
}

你可能感兴趣的:(Mock注入依赖记录)