Java 如何在Spring Boot中的所有测试用例之前只设置一次独立控制器?

Java 如何在Spring Boot中的所有测试用例之前只设置一次独立控制器?,java,spring,unit-testing,spring-boot,controller,Java,Spring,Unit Testing,Spring Boot,Controller,我正在为控制器编写单元测试。我正在模拟服务层并使用rest控制器的独立设置 ProductSupplierControllerUnitTest.java public class ProductSupplierControllerUnitTest { @Mock private ProductSupplierService productSupplierService; @InjectMocks private ProductSupplierRestContr

我正在为控制器编写单元测试。我正在模拟服务层并使用rest控制器的独立设置

ProductSupplierControllerUnitTest.java

public class ProductSupplierControllerUnitTest {

    @Mock
    private ProductSupplierService productSupplierService;

    @InjectMocks
    private ProductSupplierRestController productSupplierRestController;

    private MockMvc mockMvc;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        mockMvc = MockMvcBuilders.standaloneSetup(productSupplierRestController)
                .setControllerAdvice(new ServiceExceptionHandler()).build();
    }

    @Test
    public void productNotFound() throws Exception {

        Long incorrectProductId = 2L;

        Mockito.when(productSupplierService.getProductSuppliers(incorrectProductId, tenantId))
                .thenThrow(new EntityNotFoundException(Product.class, String.valueOf(incorrectProductId)));

        RequestBuilder requestBuilder = MockMvcRequestBuilders.get(prepareRequestUrl(incorrectProductId))
                .requestAttr(TENANT_ID, tenantId).contentType(MediaType.APPLICATION_JSON_UTF8);

        mockMvc.perform(requestBuilder).andExpect(status().isNotFound())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)).andExpect(jsonPath("$.message",
                        is(String.format("Product was not found for parameter(s) %s", incorrectProductId))));

        Mockito.verify(productSupplierService, times(1)).getProductSuppliers(incorrectProductId, tenantId);
        Mockito.verifyNoMoreInteractions(productSupplierService);
    }

    @Test
    public void getProductSuppliersSuccess() throws Exception {

        Map<String, List<? extends BaseDTO>> result = new HashMap<>(0);
        ProductSupplierDTO productSupplierDTO = new ProductSupplierDTO();
        productSupplierDTO.setSupplierId(correctSupplierId);
        productSupplierDTO.setBuyPrice(validBuyPrice);
        productSupplierDTO.setDefaultSupplier(isDefaultSupplier);

        result.put("product_suppliers", Collections.singletonList(productSupplierDTO));

        Mockito.when(productSupplierService.getProductSuppliers(productId, tenantId)).thenReturn(result);

        RequestBuilder requestBuilder = MockMvcRequestBuilders.get(prepareRequestUrl(productId))
                .requestAttr(TENANT_ID, tenantId).contentType(MediaType.APPLICATION_JSON_UTF8);

        mockMvc.perform(requestBuilder).andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
                .andExpect(jsonPath("$.product_suppliers", hasSize(1)))
                .andExpect(jsonPath("$.product_suppliers[0].supplier_id", is(correctSupplierId.intValue())))
                .andExpect(jsonPath("$.product_suppliers[0].buy_price", is(validBuyPrice)))
                .andExpect(jsonPath("$.product_suppliers[0].default_supplier", is(isDefaultSupplier)));

        Mockito.verify(productSupplierService, times(1)).getProductSuppliers(productId, tenantId);
        Mockito.verifyNoMoreInteractions(productSupplierService);
    }

    // some more tests
}

将controller和mockMvc设置为静态是否是一种好的做法?

如果使用JUnit,则使用注释@BeforeClass而不是@Before。带有此注释的方法将在类中的所有测试之前调用一次。

要使用@BeforeClass,该方法必须是静态的,因此控制器和mockmvc对象也应该是静态的。我也试过了,但它给出了初始化错误。
@RunWith(MockitoJUnitRunner.class)
public class ProductSupplierControllerUnitTest {

    @Mock
    private ProductSupplierService productSupplierService;

    @InjectMocks
    private static ProductSupplierRestController productSupplierRestController = new ProductSupplierRestController();

    private static MockMvc mockMvc =  MockMvcBuilders.standaloneSetup(productSupplierRestController)
            .setControllerAdvice(new ServiceExceptionHandler()).build();

    // tests
}