假装客户端的模拟实现不会是自动装配

时间:2016-06-20 05:58:29

标签: mocking spring-test-mvc netflix-feign spring-cloud-feign

我想测试我的春季项目。我需要在测试类中模拟假装客户端,但是正常的实现将是自动装配而不是模拟实现。这是我的代码的顶部。请帮助。

@Profile("test")
@Primary
@Component
public class PushDevClientMock implements PushDevClient {

//apiKey is needed for comminucating with GCM
private static final String apiKey = "AIzaSyC7nH1yMgfGnEHbOHCgAeOrspMReaj0hCg";
@Override
public ResponseEntity<PushInstanceResponse> getPushInstance(@PathVariable("instanceId") String instanceId) {

    ResponseEntity<PushInstanceResponse> response;
    if (instanceId == null) {
        response = new ResponseEntity<PushInstanceResponse>(HttpStatus.BAD_REQUEST);
    }
    else {
        PushInstanceResponse body = new PushInstanceResponse();
        body.setApiKey(apiKey);
        response = new ResponseEntity<PushInstanceResponse>(body,HttpStatus.ACCEPTED);
    }

    return response;
}

}

这是我的测试类:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebIntegrationTest({"server.port:0", "spring.profiles.active:test"})
public class RegistrationControllerTest {

@Autowired
WebApplicationContext wac;

@Autowired
TokenRepository tokenRepository;

private static MockMvc mockMvc;
private static ObjectMapper mapper = new ObjectMapper();
//    token and sender id are required for communicating with google
private static String senderId = "553921561995";
private static String token =
"ecdNq6_jeTM:APA91bEgWsJeIS5cXFwWrj_83EKeLWRFf1" +
        "-     lNQGXA1uWdzrfHLpd7fAY7ur6Pplc4TQuKmEDiSUhUBhDdQLwG2a_fxdgoGbDrKNLjPm2E7JOMJFjk65jtFGHrjJ39NkgABtfn6MDVUCQ";

@Before
public void setup() {
    this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).apply(springSecurity()).build();
    tokenRepository.deleteAll();
}

2 个答案:

答案 0 :(得分:0)

使用RegistrationControllerTest注释@ActiveProfiles("test")

答案 1 :(得分:0)

  1. 我从Application.java
  2. 中删除了@EnableFeignClients
  3. 像这样添加空配置类:

    @Configuration
    @Profile("!test")
    @EnableFeignClients(basePackages = "ir.pegahtech.backtory.push_api") //this is my project root
    public class FeignClientConfiguration {
    }
    
  4. 现在一切正常