Mockito.verify и Mockito.do Ничто не работает в тестовых случаях Junit - PullRequest
0 голосов
/ 13 апреля 2020

Я разместил пример кода, который соответствует моему требованию при написании тестового примера для метода create с использованием Mockito.verify () или doNothing (). Я хотел проверить, или doNothing () возвращает, когда метод create () ClassB не затрагивает DB. Я попробовал себя безразличными способами, которые не работали для меня и которые прокомментированы с выводами в Test Class. Любая помощь будет оценена

 public class ClassA {
        ClassB b=new ClassB();

        public TestPojo create(TestPojo t) {        
            TestPojo t2= b.create(t);       
            return t2;          
        }    
    }

    public class ClassB {

    public TestPojo create(TestPojo t) {
        System.out.println("class b");
            return t;       
        }

    }

public class TestPojo {

    private Integer id;
    private String name;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;

    public class ClassTest {


            @Test
            public void testCreate_1()
                throws Exception {
                ClassA testA=Mockito.spy(new ClassA());
                ClassB testB=Mockito.spy(new ClassB());         
                TestPojo test=Mockito.spy(new TestPojo());
                test.setId(1);
                //Mockito.verifyZeroInteractions(testB); -- testcase is passed but executing ClassB method but this not our intension
                //Mockito.verify(testB).create(test); --error output : Wanted but not invoked
                //Mockito.doNothing().when(testB).create(test); --error output : Only void methods can doNothing()!
                TestPojo act=testA.create(test);
                //System.out.println(act.getId());

            }
        @Before
        public void setUp()
            throws Exception {
        }   
        @After
        public void tearDown()
            throws Exception {
            // Add additional tear down code here
        }
        public static void main(String[] args) {
            new org.junit.runner.JUnitCore().run(ClassTest.class);
        }

    }

1 Ответ

1 голос
/ 13 апреля 2020

Это не работает для вас, потому что созданный экземпляр testB фактически не назначен полю b внутри ClassA. Чтобы заставить его работать, вам нужно установить свой смоделированный экземпляр и добавить проверочные проверки.

@Test
public void testCreate_1() throws Exception {
    ClassA testA = Mockito.spy(new ClassA());
    ClassB testB = Mockito.mock(ClassB.class);
    // set spied instance to testA
    testA.b = testB;
    // you don't need to spy on test, as you're not verifying anything on it
    TestPojo test = new TestPojo();
    test.setId(1);
    // execute your test method
    TestPojo act = testA.create(test);
    // verify that required create method with proper argument was called on testB 
    Mockito.verify(testB, Mockito.times(1)).create(Matchers.eq(test));
    // verify that nothing else executed on testB
    Mockito.verifyNoMoreInteractions(testB);
}

Надеюсь, это поможет!

...