我正在寻找如何在单个构造函数中注入bean和mock的方法。
@Service
public class SomeService {
private EndpointUrlProvider endpointUrlProvider;
private RestTemplate restTemplate;
@Autowired
public SomeService(EndpointUrlProvider endpointUrlProvider, RestTemplate restTemplate){
this.endpointUrlProvider = endpointUrlProvider;
this.restTemplate = restTemplate;
}
测试:
class SomeTest extends Specification {
@Autowired
EndpointUrlProvider endpointUrlProvider
RestTemplate restTemplate = Mock {
postForEntity(_, _, SomeResponse.class) >> new ResponseEntity(new SomeResponse(), HttpStatus.OK)
}
SomeService someService = new SomeService(endpointUrlProvider, restTemplate)
//some tests
}
当我触发测试时,someService中的endpointUrlProvider为null。我做错了什么?测试这个的最佳方法是什么?
答案 0 :(得分:0)
据我所知,你正试图做部分嘲笑。要注入Spring bean,首先需要TestContextManager
。因此,请使用SpringRunner
或SpringJUnit4ClassRunner
运行测试。这应该做的工作:
@RunWith(SpringRunner.class)
public class SomeServiceTest {
@Autowired
private EndpointUrlProvider endpointUrlProvider;
@Before
public setUp() {
RestTemplate restTemplate = mock(RestTemplate.class);
SomeService someService = new SomeService(endpointUrlProvider, restTemplate);
}
}