首页 > 解决方案 > 测试一起运行时失败,单独运行时通过

问题描述

我有一个测试类,当我一次运行所有测试时,所有测试都通过了,除了 getLogo()。测试 getLogo() 只有在我单独运行它时才会通过,我一点也不知道为什么。

这是我的测试课:

@WebAppConfiguration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "com.example")
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {ReceiptApplication.class})
public class PropertiesServiceTest {

    @Autowired
    private ConfigPropertiesService configPropertiesService;

    @Autowired
    private WebApplicationContext webApplicationContext;

    private MockMvc mockMvc;



    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build();
    }

    @Test
    public void uploadLogo() throws Exception {
        MockMultipartFile file = new MockMultipartFile("logo", "originalMock.jpg", null, "bar".getBytes());

        mockMvc
                .perform(multipart("/settings/uploadLogo").file(file))
                .andExpect(status().isOk());
    }

    @Test
    public void getLogo() throws Exception {
        mockMvc
                .perform(get("/settings/getLogo"))
                .andExpect(status().is(200));
    }

    @Test
    public void deleteLogo() throws Exception {
        mockMvc
                .perform(delete("/settings/deleteLogo"))
                .andExpect(status().is(200));
    }

}

我得到的例外是

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException

端点 /getLogo 如下所示:

@GetMapping(value = "/getLogo")
public String getLogo() {
    return new Gson().toJson(configPropertiesService.getLogo());
}

configPropertiesService 中的 getLogo 方法:

public byte[] getLogo() {
    ConfigPropertiesEntity configPropertiesEntity = configPropertiesRepository.findByName("com.example.logoName");

    if (configPropertiesEntity != null) {
        try {
            InputStream in = getClass().getResourceAsStream("/static/photos/" + configPropertiesEntity.getValue());
            return IOUtils.toByteArray(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

我知道为什么我得到一个 NullPointerException,这是因为当测试与其他文件一起运行时找不到该文件,在这种情况下应用程序运行到 catch 块中。但是为什么当我单独运行测试时不会发生这种情况?我如何更改测试,以便在我一起运行它们时它们也通过?

标签: javaspring-bootmockito

解决方案


推荐阅读