如何在mockito java中模拟Gson

vyu0f0g1  于 2022-11-06  发布在  Java
关注(0)|答案(1)|浏览(177)

我正在自动配置在配置类中定义的Gson对象,因为每次方法调用都要创建一个Gson对象,这样开销很大

@Configuration
    public class ConfigClass {
      @Bean
      public Gson gsonInstance(){
        Gson GSON = new Gson();
        return GSON;
      }

在我的服务课上,我给gson装了自动线。

@Service
    public class ServiceClass {
        @Autowired
        private Gson gson;

    public List<Car> getCars(String garageNum, String locationNum) {
    //Gson gson = new Gson(); Avoid this
    ResponseEntity<String> respStr =  this.restTemplate.exchange("/cars/{garageNum}/location/{locationNum}", HttpMethod.GET,null, String.class, garageNum, locationNum);
    Type collectionType = new TypeToken< List<Car>>(){}.getType();
    return gson.fromJson(respStr.getBody(), collectionType);
}

现在我无法在mockito单元测试中模拟GSON

q5lcpyga

q5lcpyga1#

您可以通过添加依赖项在Mockito中模拟Gson

<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<version>2.13.0</version>
<scope>test</scope>

也可以更改服务类

@Service
public class ServiceClass {
    protected Gson gson;

    CurrentAffairsRepository(Gson gson){
        this.gson = gson;
    }

现在在你的测试课上
@ExtendWith(MockitoExtension.class)公共类服务类测试{

@InjectMocks
private ServiceClass serviceClass;
@Mock
private RestTemplate mockRestTemplate;
private static final String GET_CARS_URL = "/car/{garageNum}/location/{locationNum}";

@BeforeEach
public void setUp() {
    Gson mockgson = new Gson();
    serviceClass.restTemplate = mockRestTemplate;
    serviceClass.gson = mockgson;
}

@Test
void testGetCurrentAffairs() {
    HttpHeaders header = new HttpHeaders();
    ResponseEntity<String> responseEntityMock = new ResponseEntity<>(
            "[{\"externalId\":\"123\"}]",
            header,
            HttpStatus.OK
    );

    when(mockRestTemplate.exchange( GET_CARS_URL, HttpMethod.GET,null, String.class, "12", "13")).thenReturn(responseEntityMock);
    List<Cars> cars = serviceClass.getCars("12","13");
    assertEquals(1,cars.size());
}

}

相关问题