如何将外部类的值传递给@Nested @Test int JUnit 5?

时间:2017-02-12 19:09:44

标签: junit5

我有OuterTest代码:

private MockMvc mockMvc;

@Mock
private Service Service;

@InjectMocks
private RestController RestController;

@BeforeEach
public void setUp() {
    MockitoAnnotations.initMocks(this);
    mockMvc = standaloneSetup(RestController)
            .build();
}

我有一个嵌套类,有测试,在我的项目上重复了几次,但需要在我的所有控制器上单独测试

     @Nested
     public class RepeatableTest extends repeatableTestSuite {

            }
        }

这是测试用例,重复了整个项目

@Test
void repeatableTestCase_shouldFailTest(MockMvc mockMvc, String url, Service service) throws Exception {

    mockMvc.perform(post(url, INVALID_VALUE))
                    .andExpect(status().isBadRequest())

            verifyZeroInteractions(service);
        }

此测试失败,因为它需要在外部类创建和配置的MockMvc和URL,我该怎么做?

1 个答案:

答案 0 :(得分:0)

解决方案是在protected MockMvc mockMvc中定义repeatableTestSuite 然后在@Nested

@Nested
public class RepeatableTest extends RepeatableTestSuite {

        @BeforeEach
        void setUp() {
            mockMvc = OuterClassTest.this.mockMvc;
            url = OuterClassTest.URL;
            service = OuterClassTest.this.service;
        }
    }