mockmvc时,spring-@autowire环境为空

hyrbngr7  于 2021-07-23  发布在  Java
关注(0)|答案(0)|浏览(276)

我使用springboot和mockmvc来测试springapi。当我试图通过isomnia或postman测试api时,api按照我的预期正常工作,@autowire注入的环境变量有一个值。但是当我使用mockmvc进行测试时,环境变量返回空值。
这是我的控制器代码:

@Autowired
private Environment env;

@GetMapping(path = { "/", "" })
@ResponseBody
@ResponseStatus(code = HttpStatus.OK)
public ReturnListDto<AttributeTypeReturnDto> getAttributeTypes(HttpServletRequest request) {
    LoggerUtilities.logInfor(logger, "Get AttributeType: " + env);

    System.out.println("HERER_0__: " + env);  //Return null value when using mockmvc to test

    ELKLogTCP logELK = new ELKLogTCP(env, request);

    try {
        //Some code call service
        logELK.setSuccess();
    } catch (Exception e) {
        logELK.setFail(e, ErrorCode.UNKNOWN_ERROR);
    }
    return data;
}

这是我的测试课:

public class AttributeTypeControllerTest {
    @Mock
    private AttributeTypeService attributeTypeService;

    @Spy
    private Environment env;
    @Autowired
    private MockMvc mockMvc;
    @InjectMocks
    private AttributeTypeController attributeTypeController;

    private AttributeType attributeType;
    private static MockedStatic mocked;

    @BeforeEach
    public void setup(){
        MockitoAnnotations.initMocks(this);
        mockMvc = MockMvcBuilders.standaloneSetup(attributeTypeController).build();
        attributeType = new AttributeType();
        attributeType.setId(1L);
    }
    @BeforeAll
    static void install() {
        mocked = mockStatic(AttributeTypeMappingDto.class);
    }
    @Test
    void getAttributeTypes() throws Exception {
        //DataTest
        ReturnListDto<AttributeTypeReturnDto> returnListDto = new ReturnListDto<>();
        AttributeTypeReturnDto attributeTypeReturnDto = Common.convertObject(attributeType, AttributeTypeReturnDto.class);
        attributeTypeReturnDto.setName("2");
        attributeTypeReturnDto.setId(1L);
        List<AttributeTypeReturnDto> returnDtos = new ArrayList<>();
        returnDtos.add(attributeTypeReturnDto);
        returnListDto.setReturnData(returnDtos);
        returnListDto.setState(true);
        List<AttributeType> attributeTypes = new ArrayList<>();
        attributeTypes.add(attributeType);
        //DataTest

        //It notworking - function call inside class 
        ELKLogTCPMockito.when(this.env.getProperty("spring.application.name")).thenReturn("iva-product-service");
        //It notworking
        Mockito.doReturn("iva-product-service").when(env).getProperty("spring.application.name");
        //Donothing not working at all
        ELKLogTCP logELK = new ELKLogTCP();
        ELKLogTCP spyUtils = Mockito.spy(logELK);
        Mockito.doNothing().when(spyUtils).setSuccess();
        Mockito.doNothing().when(spyUtils).setFail(new RuntimeException(), ErrorCode.UNKNOWN_ERROR);
            //Donothing

        mocked.when(()->AttributeTypeMappingDto.convertAttributeTypeToDto(attributeType)).thenReturn(attributeTypeReturnDto);
        mockMvc.perform(get("/api/attrType/"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.state", org.hamcrest.Matchers.equalTo(returnListDto.isState())))
                .andDo(MockMvcResultHandlers.print());
    }
}

类elklogtcp不是一个bean,我在这个类中获得了environment属性,但是在我将它传递到elklogtcp之前,它在控制器中获得null。
顺便说一句,我尝试在测试api时使用donothing()跳过日志记录,但它不起作用。
我的问题是:
测试时如何获取环境变量
顺便说一句,如何和donothing一起工作。
任何人都可以暗示我做错了什么。谢谢您!!
[编辑]
当我将环境变量解析到控制器的构造函数时,它返回mockito环境(当使用test mockito时,但当使用test mockito时,它工作正常)

public AttributeTypeController(AttributeTypeService attrTypeService, Environment env) {
        this.attrTypeService = attrTypeService;
        this.env = env;
    }

HERER_0__: org.springframework.core.env.Environment$MockitoMock$1203144333@344f4dea

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题