当前位置: 首页 > 知识库问答 >
问题:

在Mockito测试中调用方法时的NullPointerExctive

商佑运
2023-03-14

我正在用Mockito为一个项目设置jUnit测试。在被测系统(DrawingService)中调用方法时遇到问题。模拟包括图形和IDrawingRepository。

我不熟悉TDD、单元测试和一般的模拟,所以我可能犯了一些noob错误?任何帮助都将不胜感激。

以下是测试课程:

public class DrawingServiceTest {

    private DrawingService drawingService;
    private Drawing drawing;
    private IDrawingRepository repository;
    private String drawingName;

    @Before // Executed before each @Test
    public void setUp(){
        drawingService = new DrawingService();
        drawing = mock(Drawing.class);
        repository = mock(IDrawingRepository.class);
    }

    @After // Executed after each @Test
    public void tearDown(){
        //clean up code
    }

    @Test
    public void getDrawingTest() throws DrawingNotFoundException{
        drawingName = "A drawing name that exists";

        System.out.println("drawing name is: " + drawingName);
        when(repository.findByName(drawingName)).thenReturn(drawing);

        System.out.println("calling DrawingService.getDrawing(" + drawingName +")");
        drawingService.getDrawing(drawingName); // The test doesn't continue past this line

        System.out.println("verifying repository.findByName(" + drawingName +") is called");
        verify(repository).findByName(drawingName);

    }

以下是正在测试的系统:

@Service ("iDrawingService")
public class DrawingService implements IDrawingService {

    @Autowired
    private IDrawingRepository repository;  

    public List<Drawing> getDrawings() {
        return (List<Drawing>) repository.findAll();
    }

    public Drawing getDrawing(String strName) throws DrawingNotFoundException{
        Drawing drawing = repository.findByName(strName); //this line throws the NullPointerException
        if(drawing == null){
            throw new DrawingNotFoundException("No drawing found for name " + strName);
        }
        return drawing;
    }

}

共有2个答案

贺飞
2023-03-14

测试中,你可以简单地用@injectmock注释你的受试者,并用@Mock注释你所有的模拟对象,而不是使用@Mock注释你的受试者。

使用@InjectMocks你甚至不需要在这个主题上使用getter和setter。在测试中,你从不将存储库与主题联系起来。

@RunWith(MockitoJUnitRunner.class)
public class DrawingServiceTest {

     @InjectMocks private DrawingService drawingService;
     @Mock private Drawing drawing;
     @Mock private IDrawingRepository repository;
     private String drawingName;
咸正平
2023-03-14

在prod中,您的类将在spring中连接IDrawingRepository。您的测试(单元测试)并非如此。你需要手动连接。你的选择是:

  1. 让它成为你的梦想
  2. 公开IDrawingRepository的setter

我个人会使用构造函数注入,因为它是类正常工作所必需的。你的类也可以很容易地测试。

 类似资料: