模拟存储库调用的返回实体返回null

该代码段基于参数检索实体。

public void updateNotification(String status,Entity entity ) {
        Entity entity1 = null;
        try {
            switch (status) {
            case "AX":
                entity1 = this.Repository.findByTypeAndParams(
                        1,entity.getParam1(),entity.getParam2(),entity.getParam3());
                if (entity1!= null) {
                    entity1.setCurrentStatusKey("SET");
                    updateEntity(entity1);
                } else {
                    LOGGER.debug("");
                }
                break;

上述代码的测试用例:

@RunWith(springjunit4classrunner.class)
public class ServiceTest {
    @InjectMocks
    CVService cVServiceMock;

    @Mock
    RepositoryMock repositoryMock;

     @Test
            public void testUpdateOut() {
                Entity entity1 = new Entity ();
                entity1.setType(2);
                Mockito.when(repositoryMock.findByTypeAndParams(any(Integer.class),any(String.class),any(String.class))).thenReturn(entity1);
                cVServiceMock.updateNotification("AX",entity1);
            }

从测试用例执行时,entity1始终为null而不是模拟实体, 我在这里做什么错了?

lindatech 回答:模拟存储库调用的返回实体返回null

如另一个StackOverflow MariuszS' answer about Mocking static methods with Mockito中所述:

  

在Mockito顶部使用PowerMockito

     

[...]

     

更多信息:

     

PowerMockito添加了更多功能,并允许模拟私有方法,静态方法等。

有了这个,您也许应该模拟toString的实例:

Repository

不要忘记在测试类中添加注释:

// In your test method
PowerMockito.mockStatic(Repository.class);

在我的示例中,@RunWith(PowerMockRunner.class) @PowerMockRunnerDelegate(SpringRunner.class) // Since you are using SpringBoot @PrepareForTest(Repository.class) @PowerMockIgnore({"javax.management.*","javax.net.ssl.*","javax.security.*"}) // Avoid certain classloading related issues,not mandatory Mockito.when()代替。看起来可能如下:

PowerMockito.doReturn(...).when(...)

请注意,我分别用@Test public void testUpdateOut() { Entity entity1 = new Entity (); entity1.setType(2); PowerMockito.mockStatic(Repository.class); PowerMockito.doReturn(entity1).when( Repository.class,"findByTypeAndParams",// The name of the method Mockito.anyInt(),// The arguments Mockito.anyString(),Mockito.anyString(),Mockito.anyString() ); // Your test notificationServiceMock.updateNotification("AX",entity1); // And at the end of the test: PowerMockito.verifyStatic(); // It will verify that all statics were called one time } any(Integer.class)替换了您的any(String.class)anyInt()

我希望这会有所帮助!

本文链接:https://www.f2er.com/3146162.html

大家都在问