如何创建返回类型为List <tuple>的此类方法的模拟对象

时间:2018-06-20 15:09:30

标签: spring-data-jpa mockito junit4 querydsl

我正在尝试为Account Controller编写测试用例。首先,我正在创建模拟对象,但是方法的返回类型为List<Tuple>。我没有得到如何创建返回类型为List的以下方法的模拟对象

有人可以告诉我如何为以下方法创建模拟对象吗?

AccountController

    @GetMapping("/findAccountData")
    public ResponseEntity<List<Tuple>> populateGridViews(@RequestParam(value="sClientAcctId",required=false) String sClientAcctId,
                                                         @RequestParam(value="sAcctDesc",required=false) String sAcctDesc,
                                                         @RequestParam(value="sInvestigatorName",required=false)String sInvestigatorName,
                                                         @RequestParam(value="sClientDeptId",required=false) String sClientDeptId) throws Exception {
        return  ResponseEntity.ok(accService.populateGridViews(sClientAcctId, sAcctDesc,sInvestigatorName,sClientDeptId));
    }

AccountService

public List<Tuple> populateGridViews(String sClientAcctId, String sAcctDesc, String sInvestigatorName,
        String sClientDeptId)throws Exception{

    QAccount account = QAccount.account;
    QDepartment department = QDepartment.department;
    QAccountCPCMapping accountCPCMapping = QAccountCPCMapping.accountCPCMapping;
    QInvestigator investigator = QInvestigator.investigator;

    JPAQuery<Tuple> query = new JPAQuery<Tuple>(em);
    query.select(Projections.bean(Account.class, account.sClientAcctId, account.sAcctDesc, account.sLocation,
            Projections.bean(Department.class, department.sDeptName, department.sClientDeptId).as("department"),
            Projections.bean(Investigator.class, investigator.sInvestigatorName).as("investigator"),
            Projections.bean(AccountCPCMapping.class, accountCPCMapping.sCCPCode).as("accountCPC"))).from(account)
            .innerJoin(account.department, department).innerJoin(account.accountCPC, accountCPCMapping)
            .innerJoin(account.investigator, investigator);

    if (StringUtils.isNotEmpty(sClientAcctId)) {
        query.where(account.sClientAcctId.equalsIgnoreCase(sClientAcctId));
    }
  // code.......


    return query.fetch();       

}

AccountControllerTest

@RunWith(SpringRunner.class)
public class TestAccountController {

    private MockMvc mockMvc;

    @Mock
    private AccountService accountService;

    @InjectMocks
    private AccountController accountController;

    @Before
    public void setup() {
        mockMvc = MockMvcBuilders.standaloneSetup(accountController).build();
    }
       @Test
        public void populateGridViewsTest() throws Exception {

            String sClientAcctId = "1122";
            String sAcctDesc = "SRI";
            String sInvestigatorName = "Ram";
            String sClientDeptId = "1200";      

            Tuple mockedTuple = Mockito.mock(Tuple.class);      

            List<Tuple> accountObj = new ArrayList<>();
            accountObj.add(mockedTuple);

            Mockito.when(accountService.populateGridViews(sClientAcctId, sAcctDesc, sInvestigatorName, sClientDeptId))
                    .thenReturn(accountObj);

            mockMvc.perform(
                    get("/spacestudy/$ InstituteIdentifier/admin/account/findAccountData")
                    .param("sClientAcctId", "1122")
                    .param("sAcctDesc", "SRI")
                    .param("sInvestigatorName", "Ram")
                    .param("sClientDeptId", "1200")
                    .accept(MediaType.APPLICATION_JSON))
                    .andExpect(status().isOk())
                    .andDo(print());        

            Mockito.verify(accountService).populateGridViews(sClientAcctId, sAcctDesc, sInvestigatorName, sClientDeptId);

        }

堆栈跟踪

org.mockito.exceptions.misusing.MissingMethodInvocationException: 
when() requires an argument which has to be 'a method call on a mock'.
For example:
    when(mock.getArticles()).thenReturn(articles);

Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
   Those methods *cannot* be stubbed/verified.
   Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.

    at com.spacestudy.controller.AccountControllerTest.populateGridViewsTest(AccountControllerTest.java:57)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)

3 个答案:

答案 0 :(得分:0)

@AutoConfigureMockMvc
public class TickServiceTest {
    @Autowired
    private MockMvc mockMvc;
}

首先,您必须尝试使用​​此方法。而不是使用 Mockito ,而要使用 MockMvc 对象。只是告诉我您想创建 AccountController 对象还是 Account bean对象?

答案 1 :(得分:0)

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class TestAccountController {
    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private AccountService accountService;

    @Autowired
    private AccountController accountController;


       @Test
       @Transactional
        public void populateGridViewsTest() throws Exception {

            String sClientAcctId = "1122";
            String sAcctDesc = "SRI";
            String sInvestigatorName = "Ram";
            String sClientDeptId = "1200";      

            Tuple mockedTuple = Mockito.mock(Tuple.class);      

            List<Tuple> accountObj = new ArrayList<>();
            accountObj.add(mockedTuple);

            Mockito.when(accountService.populateGridViews(sClientAcctId, sAcctDesc, sInvestigatorName, sClientDeptId))
                    .thenReturn(accountObj);

            mockMvc.perform(
                    get("/spacestudy/$ InstituteIdentifier/admin/account/findAccountData")
                    .param("sClientAcctId", "1122")
                    .param("sAcctDesc", "SRI")
                    .param("sInvestigatorName", "Ram")
                    .param("sClientDeptId", "1200")
                    .accept(MediaType.APPLICATION_JSON))
                    .andExpect(status().isOk())
                    .andDo(print());        

            Mockito.verify(accountService).populateGridViews(sClientAcctId, sAcctDesc, sInvestigatorName, sClientDeptId);

        }

答案 2 :(得分:0)

您可以实现 Tuple 接口并在 thenReturn 方法中使用它。

import java.util.Arrays;

import com.querydsl.core.Tuple;
import com.querydsl.core.types.Expression;

public class MockedTuple implements Tuple {

    private final Object[] a;

    public MockedTuple(Object[] a) {
        this.a = a;
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> T get(int index, Class<T> type) {
        return (T) a[index];
    }

    @Override
    public <T> T get(Expression<T> expr) {
        return null;
    }

    @Override
    public int size() {
        return a.length;
    }

    @Override
    public Object[] toArray() {
        return a;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        } else if (obj instanceof Tuple) {
            return Arrays.equals(a, ((Tuple) obj).toArray());
        } else {
            return false;
        }
    }

    @Override
    public int hashCode() {
        return Arrays.hashCode(a);
    }

    @Override
    public String toString() {
        return Arrays.toString(a);
    }

}

测试示例:

Object[] myReturnedObject = new Object[1];
myReturnedObject[0] = value;

when(myService.getTuples(...params)).thenReturn(
List.of(new MockedTuple(myReturnedObject))
)