对于Spring AOP和mockito,是否有更新的方法?

r1zhe5dt  于 2023-01-05  发布在  Spring
关注(0)|答案(1)|浏览(139)

我已经设法解决了一个问题,与 Spring 启动aop和模拟测试服务使用的方法在Spring AOP Aspect not working using Mockito中详细说明。
有没有新的方法?

    • 编辑**从我的具体实施中添加更多详细信息。

控制器:

@RestController
public class EndpointController {
    
    private EndpointService endpointService;
    
    @Autowired    
    public EndpointController(EndpointService endpointService) {
        this.endpointService = endpointService;
    }

    @PostMapping(path = "/endpoint", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    private @ResponseBody EndpointResponse doSomething(/* ... */, @RequestBody SomeObject someObject) throws Exception {
        return endpointService.doSomething(someObject);
    }
}

在我的测试类中,我有:

@RunWith(SpringRunner.class)
public class EndpointControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void shouldBeSuccessfulAccessingTheEndpoint() throws Exception {
        SomeObject someObject = new SomeObject(/* values */);

        ObjectMapper mapper = new ObjectMapper();
        String payload = mapper.writeValueAsString(someObject);

        mockMvc.perform(post("/endpoint").contentType(MediaType.APPLICTION_JSON).content(payload)).andExpect(status().isOK));
    }
}

失败,抛出NullPointerException异常,调试时endpointService始终为空。
有什么想法吗?

luaexgnf

luaexgnf1#

现在可以使用注解@MockBean,它是 Spring 测试中的某种 Package mockito。

@RunWith(SpringRunner.class)
public class ExampleTests {

     @MockBean
     private ExampleService service;

     @Autowired
     private UserOfService userOfService;

     @Test
     public void testUserOfService() {
         given(this.service.greet()).willReturn("Hello");
         String actual = this.userOfService.makeUse();
         assertEquals("Was: Hello", actual);
     }

     @Configuration
     @Import(UserOfService.class) // A @Component injected with ExampleService
     static class Config {
     }
 }

https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/mock/mockito/MockBean.html

相关问题