簡體   English   中英

在 SpringBoot API 中測試時 controller 上出現 NullPointerException - Mocking

[英]NullPointerException on controller when testing in SpringBoot API - Mocking

我不知道為什么,但是當我嘗試使用 MVC 測試 controller 中的任何方法時,我的代碼給了我一個 nullPointerException 錯誤。 這里我放了部分代碼:

我的controller (僅限第一種方法):

@RestController
@RequestMapping(path = "/companias")
public class ControllerAPI {


    @Autowired
    private final CompaniaServiceImpl companiaService;

    public ControllerAPI(CompaniaServiceImpl companiaService) {
        this.companiaService = companiaService;
    }

    @ResponseStatus(HttpStatus.OK)
    @GetMapping("/{companiaId}/{field_name}")
    public Map<String, List<Object>> getByField(
        @PathVariable("companiaId") Long companiaId,
        @PathVariable("field_name") String fieldName) {

        return companiaService.getCompaniaByfield(companiaId, fieldName);

    }

這是我的服務(我試圖模擬的服務):

@Service
@Slf4j
public class CompaniaServiceImpl implements CompaniaService {


    private final CompaniaRepository companiaRepository;
    private final DefaultGroupRepository defaultGroupRepository;
    private final OfficeRepository officeRepository;

    @Autowired
    public CompaniaServiceImpl(CompaniaRepository companiaRepository, DefaultGroupRepository defaultGroupRepository, OfficeRepository officeRepository) {
        this.companiaRepository = companiaRepository;
        this.defaultGroupRepository = defaultGroupRepository;
        this.officeRepository = officeRepository;
    }


    public Map<String, List<Object>> getCompaniaByfield(Long companiaId, String fieldName) {

        if (companiaRepository.existsById(companiaId)) {
            Map<String, Function<Compania, Object>> mapCompania = Map.of(
                "name", Compania::getName,
                "dominio", Compania::getDominio,
                "altas", Compania::getAltas,
                "bajas", Compania::getBajas
            );

            Compania c = companiaRepository.findCompaniaById(companiaId);
            Function<Compania, Object> retriever = mapCompania.get(fieldName);


            return Collections.singletonMap("success", List.of(retriever.apply(c)));
        }
        else throw new IllegalStateException(
            "Compania con id (" + companiaId + ") no existe"
        );

    }

這是我的controller 測試

@ExtendWith(SpringExtension.class)
@ContextConfiguration
class ControllerAPITest {

    String token = "xxx";

    @InjectMocks
    private ControllerAPI controllerAPI;

    private CompaniaServiceImpl companiaService = Mockito.mock(CompaniaServiceImpl.class);

    private MockMvc mockMvc;

    @Before
    public void setup() throws Exception{

        MockitoAnnotations.initMocks(this);

        this.mockMvc = MockMvcBuilders.standaloneSetup(controllerAPI).build();
    }


    @Test
    void getByField() throws Exception {
        Map<String, List<Object>> response = Collections.singletonMap("success", List.of("nombre1"));
        Mockito.when(companiaService.getCompaniaByfield(1L,"name")).thenReturn(response);

        this.mockMvc.perform(
                get("/companias/{companiaId}/{field_name}", 1L, "name")
                    .header("authorization", "Bearer " + token)
                    .contentType(MediaType.APPLICATION_JSON))
            .andDo(print())
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.success[0]").isNotEmpty())
            .andExpect(jsonPath("$.success[0]").value("nombre1"));
    }

還有給我的NullPointerException 錯誤

java.lang.NullPointerException
    at database.configuration.controller.ControllerAPITest.getByField(ControllerAPITest.java:69)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:686)
    at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
    at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
    at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:212)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:208)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:137)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:71)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:248)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$5(DefaultLauncher.java:211)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:226)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:199)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:132)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)

它在this.mockMvc.perform(我不知道為什么我不能模擬我的服務的行中給我這個錯誤。如果你能幫助我,我會非常感激

測試中的主要問題是您在單個測試中混合了 JUnit 4 注釋和 JUnit5。 @Before來自 JUnit4,因此設置永遠不會運行,因此不會創建依賴項或模擬。 因此NullPointerException因為沒有注入。

在您的代碼中,您應該使用CompaniaService接口而不是CompaniaServiceImpl 你已經定義了一個你應該使用的接口。

更改您的 controller。

@RestController
@RequestMapping(path = "/companias")
public class ControllerAPI {


    private final CompaniaService companiaService;

    public ControllerAPI(CompaniaService companiaService) {
        this.companiaService = companiaService;
    }

您不需要字段上的@Autowired ,因為注入是通過構造函數完成的。

現在,對於您的測試,您可以做幾件事。

  1. @Before替換為@BeforeEach ,這是用於標記方法的JUnit5 注釋。 您不需要@ExtendsWith@ContextConfiguration

  2. 而不是@ExtendsWith(SpringExtension.class)使用MockitoExtension ,使用@BeforeEach但不初始化模擬。

  3. 使用@WebMvcTest@MockBean並讓 Spring Boot 為您處理注入和模擬創建。

使用正確的注釋

class ControllerAPITest {

    String token = "xxx";

    @InjectMocks
    private ControllerAPI controllerAPI;

    @Mock
    private CompaniaService companiaService;

    private MockMvc mockMvc;

    @BeforeEach
    public void setup() throws Exception{

        MockitoAnnotations.initMocks(this);

        this.mockMvc = MockMvcBuilders.standaloneSetup(controllerAPI).build();
    }


   @Test
   void getByField() throws Exception {  ... }

使用MockitoExtension

@ExtendsWith(MockitoExtension.class)
class ControllerAPITest {

    String token = "xxx";

    @InjectMocks
    private ControllerAPI controllerAPI;

    @Mock
    private CompaniaService companiaService;

    private MockMvc mockMvc;

    @BeforeEach
    public void setup() throws Exception{
        this.mockMvc = MockMvcBuilders.standaloneSetup(controllerAPI).build();
    }

   @Test
   void getByField() throws Exception {  ... }

使用@WebMvcTest

@WebMvcTest(ControllerAPI.class)
class ControllerAPITest {

    String token = "xxx";

    @MockBean
    private CompaniaService companiaService;

    @Autowired
    private MockMvc mockMvc;


   @Test
   void getByField() throws Exception {  ... }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM