您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

使用具有独立上下文和SpringBoot 1.2.5的MockMvcBuilders进行文件上传的单元测试

使用具有独立上下文和SpringBoot 1.2.5的MockMvcBuilders进行文件上传的单元测试

我混合了lkrnak的建议和Mockito的@Spy功能。我使用REST-Assured进行通话。所以,我做了如下:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MyApplication.class)
@WebAppConfiguration
@IntegrationTest({"server.port:0"})
public class ControllerTest{

    {
      System.setProperty("spring.profiles.active", "unit-test");
    }


    @Autowired
    @Spy
    AService aService;

    @Autowired
    @InjectMocks
    MyRESTController controller;

    @Value("${local.server.port}")
    int port;


  @Before public void setUp(){
    RestAssured.port = port;

    MockitoAnnotations.initMocks(this);
  }

  @Test
  public void testFileUpload() throws Exception{
        final File file = getFileFromResource(fileName);

        doNothing().when(aService)  
             .doSomethingOnDBWith(any(multipartfile.class), any(String.class));

        given()
          .multiPart("file", file)
          .multiPart("something", ":(")
          .when().post("/file-upload")
          .then().(HttpStatus.CREATED.value());
    }
}

服务定义为

@Profile("unit-test")
@Primary
@Service
public class MockAService implements AService {
  //empty methods implementation
}
Java 2022/1/1 18:18:35 有434人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶