java模拟类在单元测试执行时显示为null

camsedfj  于 2021-07-16  发布在  Java
关注(0)|答案(1)|浏览(610)

我编写了一个如下所示的单元测试,下面是我看到的另一个单元测试的示例,但是由于某种原因,当我运行测试时,我正在测试 serviceProperties 对象显示为 null ,我认为这种方法会给我一个嘲笑的价值。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
@Category({ UnitTests.class })
public class MyTest {

    @Mock
    private OAuth2RestTemplate serviceRestTemplate;

    @Mock
    // had to make this static to use inside TestConfiguration
    static
    serviceProperties serviceProperties;

    @Configuration
    @EnableConfigurationProperties
    @Import({ PropertiesTestConfiguration.class, RestTestConfiguration.class })
    static class TestConfiguration {

        @Bean
        MyInterface MyInterface() {
            return new MyInterface(serviceProperties);
        }
    }

    @Autowired
    MyInterface MyInterface;

    @Test
    public void getServiceResponse_Success() throws ServiceException {

        Mockito.when(serviceProperties.getUrl()).thenReturn("http://test_url");

        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(serviceProperties.getUrl() + VALID_NUMBER + HEADER_ENDPOINT);

        ResponseEntity<String> mockResponseEntity = new ResponseEntity<String>(mockResponseBody, HttpStatus.OK);

        thrown.none();

        MyInterface.getClaimByClaimId(VALID_CLAIM_NUMBER);
    }

}
4jb9z9bj

4jb9z9bj1#

这个 @Mock 如果不使用注解对类进行注解,则注解无效 @ExtendWith(MockitoExtension.class) .

相关问题