【问题标题】:The service is set to null in my Junit Test该服务在我的 Junit 测试中设置为 null
【发布时间】:2021-03-20 19:55:11
【问题描述】:

我正在为我的 Springboot 应用程序创建测试。应用程序通过 Get 调用,在 RequestBody 中传递我的“CarRequest”

public class CarsRequest implements Serializable {
    private String name;
    private String plate ;
    private  String price;
}

它将与该数据相关的汽车规格返回给我

{
   "name":"",
   "plate":"",
   "price":"",
   "brand":"",
   "kilometers":"",
   "revisiondate":"",
   "owner":""
}

我使用 Mockito 做了这个简单的测试,但我不明白为什么我的服务默认设置为 null,这会将所有内容都抛出 NullPointErexception

public class CarTest {
    @Autowired
    private MockMvc mockMvc;
    @MockBean
    private CarService service;
    @Autowired
    ObjectMapper objectMapper;
    @Test
    public void TestOk() throws Exception{
        CarsRequest carsRequest = new CarsRequest();
        Car  car = new Car();
        List<Car> cars = new ArrayList<>();
        //septum the fields of cars and add them to the list
        cars.add(car);
        Mockito.when(
                service.getByPlate("bmw",
                        "TG23IO", "1500")).thenReturn(cars);
        RequestBuilder requestBuilder = MockMvcRequestBuilders.get(
                "/garage/cars").accept(
                MediaType.APPLICATION_JSON);
        MvcResult result = mockMvc.perform(requestBuilder).andReturn();
        System.out.println(result.getResponse());
        String expected = "{name:"bmw","plate":"TG23IO","price":"1500","brand":"POL","kilometers":"80000","revisiondate":"2016-03-15","owner":"JohnLocke"}";
        JSONAssert.assertEquals(expected, result.getResponse()
                .getContentAsString(), false);
    }
}

下面我还添加了我的 CarService

@Service
public class CarService {
    @Autowired
    CarRepository carRepository;
    @Autowired
    ObjectMapper objectMapper;
    public List<Cars> getByContratto(String name, String plate, String price) throws JsonProcessingException {
        //some code, extraction logic
        return cars;
    }
}

应用程序运行良好,只有测试不起作用。作为测试写作的新手,我无法弄清楚我的 Carservice 上的 null 是什么原因造成的。 如果需要,我也可以包含 Controller Get 和存储库,但我认为它们无济于事

【问题讨论】:

    标签: java spring junit mocking


    【解决方案1】:

    我相信您正在尝试测试控制器。因此,在测试类的顶部包含以下注释。

    @SpringBootTest
    @AutoConfigureMockMvc
    @RunWith(SpringRunner.class)
    

    另外,我可以看到在测试代码中引用了 CarService,而共享的服务代码包含 DocumentService。

    【讨论】:

    • 如果只需要 mvc 部分,这将加载完整的上下文,更好的选择是 @WebMvcTest
    【解决方案2】:

    尝试将@RunWith(SpringRunner.class) 添加到您的测试类中。

    我怀疑您正在使用Junit 4 进行测试。在Junit 4 你需要添加 @RunWith(SpringRunner.class) 在您的测试中,否则所有注释都将被忽略。 For more info check the docs here 46.3 Testing Spring Boot Applications 是回答您问题的部分。

    不过,如果可能,我建议您迁移到 Junit 5

    @RunWith(SpringRunner.class)
    public class CarTest {
        @Autowired
        private MockMvc mockMvc;
        @MockBean
        private CarService service;
        @Autowired
        ObjectMapper objectMapper;
        @Test
        public void TestOk() throws Exception{
            // code here
            JSONAssert.assertEquals(expected, result.getResponse()
                    .getContentAsString(), false);
        }
    }
    

    【讨论】:

    • 嗨,我尝试了您的解决方案,但我将测试分为失败的“JunitVintage”和有效的“JunitJupiter”,为什么会这样?
    • @Numero21 添加@SpringBootTest/@WebMvcTest 而不是@RunWith 迁移所有@Test 注释以从import org.junit.jupiter.api.Test 导入而不是import org.junit.Test; 所以你有JUNIT5 因此没有JunitVintage
    【解决方案3】:

    假设您只想测试您的控制器层(因为您使用的是 mockMvc)并且您使用的是 Junit 4(看起来像您的代码),您应该按如下方式编写测试用例

    @RunWith(SpringRunner.class)
    @WebMvcTest(SomeController.class)
    public class CarTest {
        @MockBean
        private SomeService service;
    
        @Autowired
        private MockMvc mockMvc;
    
        @Test
        public void shouldPassTest() {
            BDDAssertions.assertThat(service).isNotNull();
        }
    }
    

    注意:示例中的测试方法无关紧要,我添加只是为了说明。

    如果有帮助,请告诉我们。

    【讨论】:

    • 嗨,我尝试了您的解决方案,但我将测试拆分为失败的“JunitVintage”和有效的 JunitJupiter,为什么会这样做?
    • 那么你的设置有问题,这应该可以工作,什么失败了?使用老式 API 时服务对象是否为空?
    猜你喜欢
    • 1970-01-01
    • 2020-09-24
    • 2013-06-30
    • 1970-01-01
    • 2010-12-13
    • 1970-01-01
    • 2015-10-28
    • 2018-07-19
    • 1970-01-01
    相关资源
    最近更新 更多