Featured image of post 如何將Junit的測試粒度控制在最小單元

如何將Junit的測試粒度控制在最小單元

如何讓單元測試不涉及SpringBoot, Filter, Interceptor, AspectJ

在Junit5中,有對一些Junit的測試的註解進行調整

比如說

Junit4Junit5
測試用框架的選擇@RunWith(MockitoJUnitRunner.class)@ExtendWith(MockitoExtension.class)

當測試會使用到SprintBoot框架時,應該要使用@ExtendWith(SpringExtension.class),@MockBean來調用

若測試不想涉及SprintBoot的時候@ExtendWith(MockitoExtension.class),以及@Mock, @InjectMocks,並且使用MockMvcBuilders.standaloneSetup來設置獨立測試,以下是Code的示範

1
2
3
4
5
6
7
8
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.assertj.core.api.Assertions;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.assertj.core.api.Assertions.assertThat;

/**
 * @author Hoxton on 2022/11/30
 */
@ExtendWith(MockitoExtension.class)
public class UserControllerTest {

    @Mock //Controller調用的Service
    UserService userService;
    @InjectMocks //要測試的Cotroller
    UserController userController;
    
    MockMvc mockMvc; //模擬Mvc

    @BeforeEach
    public void setMockMvc(){
        MockMvcBuilders.standaloneSetup(userController).build();
    }
    
   	@Test
    void testMethod_situation_returnWhat(){
        given(someObject.someMethod()).willReturn("someting");
       	// ... 設置
        
        MockHttpServletResponse response = mvc.perform(get("someUrl")).andReturn().getResponse();
        assertThat("something").isEqualTo("thatThing");
    }
}