初始化TestNG单元测试中的自动连接对象



这是我的代码:

@Service("MyCode")
public class CodeImpl implements CodeI {
    @Autowired
    private CodeMapper codeMapper;
    @Autowired
    private CodeAppService codeAppService;
    @Override
    public CodePOJO getCode(String myId) {
        CodeDTO codeDTO = codeAppService.getOne(myId);
        return codeMapper.mapCode(codeDTO);
    }
}

这是我写的单元测试:

public class CodeImplTest {
    @Tested(fullyInitialized = true)
    CodeImpl codeImpl;
    @Injectable
    CodeAppService mockedCodeAppService;
    @Injectable
    CodeMapper mockedCodeMapper;
    @BeforeMethod
    public void setup_mocks() {
        codeImpl = new CodeImpl();
    }
    @Test
    public void testGetCode() throws Exception {
        final CodeDTO codeDTO = new codeDTO();
        codeDTO.setName("my name")
        new NonStrictExpectations() {{
            mockedCodeAppService.getOne(anyString);
            result = codeDTO;
        }};
        CodePOJO returnedCodePOJO = codeImpl.getCode("1");
        assertThat(returnedCodePOJO, is(instanceOf(CodePOJO.class)));
        assertThat(returnedCodePOJO.getName(), is("my name"));
    }
}

我得到以下未初始化的异常:

  java.lang.AssertionError: 
      Expected: is "my name"
      but: was null
  at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)   
  at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:8)    
  at com.dev.impl.CodeImplTest.testGetCode(CodeImplTest.java:74)

我试着在论坛上搜索过,但没有任何答案。

任何帮助都将不胜感激。

谢谢。

您只为codeAppService.getOne()准备了行为,但在代码中,该调用的结果随后传递给codeMapper.mapCode()

我会试试:

new NonStrictExpectations() {{
    mockedCodeAppService.getOne(anyString);
    result = codeDTO;
    mockedCodeMapper.mapCode(codeDTO);
    result = codeDTO;
}};

相关内容

  • 没有找到相关文章

最新更新