Junit的新功能,欢迎任何针对以下问题的解决方案。 我有一个主要类,
@Service
public class MainClass extends AbstractClass {
@Autowired
ClassA a;
@Autowired
ObjectMapper mapper;
public void methodA(){
....
AnotherClass obj= (AnotherClass)mapper.readerFor(AnotherClass.class).readValue(SOME_CODE);
.......
}
测试类是,
@RunWith(PowerMockRunner.class)
@PrepareForTest({MainClass.class})
public class MainClassTest {
@Mock
ClassA a;
@Mock
ObjectMapper mapper;
@InjectMocks
MainClass process = new MainClass();
//I have to do somthing for Autowired mapper class of main in test class as well
@Test
public void testProcessRequest() throws Exception{
process.methodA()
}
在测试时,主类中的mapper对象变为null,是的,我知道我没有进行任何类型的初始化。 是否有更好的方法来编写junit映射器。 注意:我尝试使用@Mock for ObjectMapper,它会在“readerFor”处抛出异常。 提前谢谢。
答案 0 :(得分:0)
您不必使用Mockito / powerMock。只需使用弹簧靴测试。 像这样:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SomeServiceTest {
@Autowired
private SomeService service;
@Autowired
private ObjectMapper om;
@Test
public void try_Me(){
System.out.println(om);
}
}
为您的问题添加更多信息。 如果你真的想使用mockito作为ObjectMapper,你应该准备模拟。如果不是在调用readerFor(...)时,mock默认返回null,稍后在readValue方法中,你得到一个nullpointer。
模拟的基本准备可能是:
ObjectReader or = Mockito.mock(ObjectReader.class);
Mockito.when(or.readValue(Mockito.anyString())).thenReturn(new instance of your object);
Mockito.when(mapper.readerFor(User.class)).thenReturn(or);