Java 在我的Junit测试中,服务被设置为null

Java 在我的Junit测试中,服务被设置为null,java,spring,junit,mocking,Java,Spring,Junit,Mocking,我正在为我的Springboot应用程序创建测试。应用程序通过Get调用,在RequestBody中传递我的“CarRequest” public class CarsRequest implements Serializable { private String name; private String plate ; private String price; } 它还给了我与该数据相关的汽车规格 { "name":""

我正在为我的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);
    }
}
公共类卡特斯特{
@自动连线
私有MockMvc-MockMvc;
@蚕豆
私家车服务;
@自动连线
对象映射器对象映射器;
@试验
public void TestOk()引发异常{
CarsRequest CarsRequest=新的CarsRequest();
汽车=新车();
List cars=new ArrayList();
//分隔汽车字段并将其添加到列表中
cars.add(car);
莫基托,什么时候(
服务。getByPlate(“宝马”,
“TG23IO”、“1500”)。然后返回(cars);
RequestBuilder RequestBuilder=MockMvcRequestBuilders.get(
“/车库/汽车”)。接受(
MediaType.APPLICATION_JSON);
MvcResult result=mockMvc.perform(requestBuilder.andReturn();
System.out.println(result.getResponse());
字符串expected=“{name:“bmw”,“plate:”TG23IO”,“price:”1500”,“brand:”POL”,“km:”80000”,“revisiondate:”2016-03-15”,“owner:”JohnLocke“}”;
JSONAssert.assertEquals(应为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;
    }
}

@服务
公营汽车服务{
@自动连线
进位进位进位进位;
@自动连线
对象映射器对象映射器;
公共列表getByContratto(字符串名称、字符串模板、字符串价格)抛出JsonProcessingException{
//一些代码,提取逻辑
返回车辆;
}
}
应用程序运行良好,只是测试不起作用。作为一个测试写作的新手,我不知道我的Carservice上的null是什么原因。
如果需要,我还可以包括控制器Get和存储库,但我认为它们没有帮助

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

@SpringBootTest
@AutoConfigureMockMvc
@RunWith(SpringRunner.class)

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

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

@SpringBootTest
@AutoConfigureMockMvc
@RunWith(SpringRunner.class)
另外,我可以看到,在测试代码中,CarService正在被引用,而共享的服务代码包含DocumentService。

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

@SpringBootTest
@AutoConfigureMockMvc
@RunWith(SpringRunner.class)
我怀疑您正在使用JUnit4进行测试。在JUnit4中,您需要添加
@RunWith(SpringRunner.class)
在测试中,否则将忽略所有注释。 . <代码>46.3测试Spring Boot应用程序是回答您问题的部分

但是,如果可能的话,我建议您迁移到JUnit5

@RunWith(SpringRunner.class)
公共类卡特斯特{
@自动连线
私有MockMvc-MockMvc;
@蚕豆
私家车服务;
@自动连线
对象映射器对象映射器;
@试验
public void TestOk()引发异常{
//代码在这里
JSONAssert.assertEquals(应为result.getResponse())
.getContentAsString(),false);
}
}
尝试将
@RunWith(SpringRunner.class)
添加到测试类中

@SpringBootTest
@AutoConfigureMockMvc
@RunWith(SpringRunner.class)
我怀疑您正在使用JUnit4进行测试。在JUnit4中,您需要添加
@RunWith(SpringRunner.class)
在测试中,否则将忽略所有注释。 . <代码>46.3测试Spring Boot应用程序是回答您问题的部分

但是,如果可能的话,我建议您迁移到JUnit5

@RunWith(SpringRunner.class)
公共类卡特斯特{
@自动连线
私有MockMvc-MockMvc;
@蚕豆
私家车服务;
@自动连线
对象映射器对象映射器;
@试验
public void TestOk()引发异常{
//代码在这里
JSONAssert.assertEquals(应为result.getResponse())
.getContentAsString(),false);
}
}

假设您只想测试控制器层(因为您使用的是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();
    }
}
注意:在示例中,测试方法是不相关的,我添加它只是为了说明


让我们知道它是否有用。

假设您只想测试您的控制器层(因为您使用的是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();
    }
}
注意:在示例中,测试方法是不相关的,我添加它只是为了说明


让我们知道它是否有帮助。

您好,我尝试了您的解决方案,但我将测试分为“JUnitVentage”和“JunitJupiter”两部分,这两部分都失败了,为什么要这样做?您的设置出现了一些问题,这应该有效,什么部分失败了?使用vintage API时服务对象是否为空?您好,我尝试了您的解决方案,但我将测试分为失败的“JUnitVentage”和有效的JunitJupiter,为什么它会这样做?您的设置存在一些问题,这应该有效,什么失败了?使用vintage API时服务对象是否为空?您好,我尝试了您的解决方案,但我将测试分为失败的“JUnitVentage”和有效的“JunitJupiter”,为什么会这样做?@Numero21添加
@SpringBootTest
/
@WebMvcTest
而不是
@RunWith
迁移所有
@Test
注释,从
导入org.junit.jupiter.api.Test
而不是
导入org.junit.Test所以你有JUNIT5,因此没有JunitVintageHi,我试过你的sol