我想将JUnit测试套件添加到一个已经启动并运行的spring mvc应用程序中。特别是我想测试控制器API。你能推荐一个特别的手术吗?我不想使用任何spring-boot库/解决方案。先谢了。Giuseppe
gk7wooem1#
我通常用JUnit和Mockito测试Controllers API,如下所示。
@ExtendWith(MockitoExtension.class) public class MemberApiControllerTest { @Mock private MemberService memberService; @InjectMocks private MemberApiController memberApiController; private MockMvc mockMvc; private ObjectMapper objectMapper; @BeforeEach public void setUp() { mockMvc = MockMvcBuilders.standaloneSetup(memberApiController) .build(); objectMapper = new ObjectMapper(); } @Test @DisplayName("Add Member Test") public void addMemberTest() throws Exception { //given Member member = Member.builder() .id("id") .password("password") .email("email") .nick("nick") .build(); //when ResultActions resultActions = mockMvc.perform(post("/api/member") .contentType(MediaType.APPLICATION_JSON_VALUE) .content(objectMapper.writeValueAsString(member))); //then resultActions.andExpect(status().isOk()); verify(memberService, times(1)).addMember(any(Member.class)); } }
字符串
1条答案
按热度按时间gk7wooem1#
我通常用JUnit和Mockito测试Controllers API,如下所示。
字符串