我对Mockito和jUnit非常新,我尝试学习正确的TDD方式.我需要几个例子,以便我可以使用mockito来编写单元测试

以下是我的控制器类,它上传文件并对此文件输入执行一些操作.

@Controller
@RequestMapping("/registration")
public class RegistrationController {

    @Autowired
    private RegistrationService RegistrationService;

    @Value("#{Properties['uploadfile.location']}")
    private String uploadFileLocation;

    public RegistrationController() {

    }

    @RequestMapping(method = RequestMethod.GET)
    public String getUploadForm(Model model) {
        model.addAttribute(new Registration());
        return "is/Registration";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String create(Registration registration,BindingResult result,ModelMap model)
            throws NumberFormatException,Exception {

        File uploadedFile = uploadFile(registration);
        List<Registration> userDetails = new ArrayList<Registration>();
        processuploadedFile(uploadedFile,userDetails);

        model.addAttribute("userDetails",userDetails);

        return "registration";
    }

    private File uploadFile(Registration registration) {

        Date dt = new Date();
        SimpleDateFormat format = new SimpleDateFormat("MM_dd_yyyy_HH_mm_ss");
        File uploadedFile = new File(uploadFileLocation
                + registration.getFileData().getoriginalFilename() + "."
                + format.format(dt));

            registration.getFileData().transferTo(uploadedFile);

        return uploadedFile;
    }

    private void processuploadedFile(File uploadedFile,List<Registration> userDetails)
            throws NumberFormatException,Exception {

        registrationService.processFile(uploadedFile,userDetails);
    }

}

可以任何身体请建议一些例子我如何使用mockito来编写测试用例?

编辑
我已经写下了下面的测试类,但如何进一步

@RunWith(MockitoJUnitRunner.class)
@ContextConfiguration(locations = { "/meta-inf/spring/applicationContext.xml"})
public class BulkRegistrationControllerTest {

    @InjectMocks
    private RegistrationService registrationService= new RegistrationServiceImpl();
    @Mock
    private final ModelMap model=new ModelMap(); 

    @InjectMocks
    private ApplicationContext applicationContext;

    private static MockHttpServletRequest request;
    private static MockHttpServletResponse response;

    private static RegistrationController registrationController;

    @BeforeClass
    public static void init() {

           request = new MockHttpServletRequest();
           response = new MockHttpServletResponse();           
           registrationController = new RegistrationController();

    }
    public void testCreate()
    {
        final String target = "bulkRegistration";
        BulkRegistration bulkRegistration=new BulkRegistration();
        final BindingResult result=new BindingResult();     

        String nextPage=null;       
        nextPage = bulkRegistrationController.create(bulkRegistration,result,model);
        assertEquals("Controller is not requesting the correct form",nextPage,target);

    }

}

解决方法

有几件事你似乎已经在你的测试中.有集成测试和单元测试.集成测试将测试所有连接的东西(或几乎所有的东西),所以你使用Spring配置文件非常接近真实的实例,并将实际的对象示例注入到被测试的类中.这大部分是我使用@ContextConfiguration,但我结合使用@RunWith(SpringJUnit4ClassRunner.class)

如果您使用Mockito(或任何嘲笑框架),通常是因为您想要从其他类的实际实现中隔离正在测试的类.所以,例如,不必设法让你的RegistrationService抛出一个NumberFormatException来测试这个代码路径,你只需要告诉模拟注册服务.还有很多其他的例子,使用mocks比使用真实类实例更方便.

所以,这个迷你课完成了.这是我将如何重新编写你的测试类(附有一个额外的例子,并在评论的过程中).

@RunWith(MockitoJUnitRunner.class)
public class RegistrationControllerTest {

    // Create an instance of what you are going to test.
    // When using the @InjectMocks annotation,you must create the instance in
    // the constructor or in the field declaration.
    @InjectMocks
    private RegistrationController controllerUT = new RegistrationController();

    // The @Mock annotation creates the mock instance of the class and
    // automatically injects into the object annotated with @InjectMocks (if
    // possible).
    @Mock
    private RegistrationService registrationService;
    // This @Mock annotation simply creates a mock instance. There is Nowhere to
    // inject it. Depending on the particular circumstance,it may be better or
    // clearer to instantiate the mock explicitly in the test itself,but we're
    // doing it here for illustration. Also,I don't kNow what your real class
    // is like,but it may be more appropriate to just instantiate a real one
    // than a mock one.
    @Mock
    private ModelMap model;
    // Same as above
    @Mock
    private BulkRegistration bulkRegistration;
    // Same as above
    @Mock
    private FileData fileData;

    @Before
    public void setUp() {
        // We want to make sure that when we call getFileData(),it returns
        // something non-null,so we return the mock of fileData.
        when(bulkRegistration.getFileData()).thenReturn(fileData);
    }

    /**
     * This test very narrowly tests the correct next page. That is why there is
     * so little expectation setting on the mocks. If you want to test other
     * things,such as behavior when you get an exception or having the expected
     * filename,you would write other tests.
     */
    @Test
    public void testCreate() throws Exception {
        final String target = "bulkRegistration";
        // Here we create a default instance of BindingResult. You don't need to
        // mock everything.
        BindingResult result = new BindingResult();

        String nextPage = null;
        // Perform the action
        nextPage = controllerUT.create(bulkRegistration,model);
        // Assert the result. This test fails,but it's for the right reason -
        // you expect "bulkRegistration",but you get "registration".
        assertEquals("Controller is not requesting the correct form",target);

    }

    /**
     * Here is a simple example to simulate an exception being thrown by one of
     * the collaborators.
     * 
     * @throws Exception
     */
    @Test(expected = NumberFormatException.class)
    public void testCreateWithNumberFormatException() throws Exception {
        doThrow(new NumberFormatException()).when(registrationService)
                .processFile(any(File.class),anyList());
        BindingResult result = new BindingResult();
        // Perform the action
        controllerUT.create(bulkRegistration,model);
    }
}

java – 如何使用mockito编写控制器类的单元测试用例的更多相关文章

  1. 如何通过代码设置iOS的系统时区?

    我想通过代码在iOS中设置系统时区,日期时间.任何想法或私人api帮助我?示例:将时区设置为GMT8,将日期时间设置为2013年8月10日晚上8:30.怎么做?

  2. ios – 如何为NSNotification编写单元测试

    我在swift工作,我想刷新一个页面,所以我使用通知发送它,我在一个ViewController中发布通知并在另一个中添加观察者,它工作正常.我想要做的是在swift中添加单元测试.我查了很多网站但是没能做到.我是新手,不知道从哪里开始.基本上工作是,当我点击按钮通知被发布时,并且当加载下一个视图控制器时,添加通知观察者.我该怎么做单元测试提前致谢编辑:码并添加观察者解决方法一般的解决方案是:使用

  3. 如何在iOS中为预期的assert / assertionFailure编写单元测试?

    这里的问题是,当someString参数为空字符串时,您可以保证函数不会失败–在您的实际应用程序中.这是因为断言不在发布版本中运行.结果是你可以在开发过程中使用assert作为调试的一种形式,但如果这种情况在现实生活中发生,你应该按顺序处理它,而不是崩溃.因此测试断言“发生”是否真的不是一种有效的单元测试技术,这就是为什么你以这种方式使用它的麻烦.

  4. xcode – 如何在不影响单元测试目标构建的情况下更改发布目标的名称?

    我有一个发布目标和一个测试目标,我想更改发布目标的名称,但如果我这样做,我开始在测试目标中获得链接错误.由于它们是单元测试,我认为在测试目标中不会/应该是对发布目标的依赖,但显然存在.链接错误是:在重命名之前,XYZ.app是发布目标的名称.是否有自动或快速更新单元测试目标的方法,以便它保持步调状态?

  5. ios – 如何从Swift中的每个UI测试断言开始使用空Core数据?

    提前致谢!

  6. ios – 可以测试IBAction吗?

    对IBOutlets进行单元测试有点容易,但IBActions呢?我试图找到一种方法,但没有任何运气.有没有办法在ViewController中的IBAction和nib文件中的按钮之间进行单元测试连接?解决方法对于完整的单元测试,每个插座/操作需要三个测试:>插座是否连接到视野?

  7. ios app如何“知道”运行单元测试

    我知道我可以用xcodebuild开始我的应用程序的单元测试,但我想知道是什么告诉应用程序在启动期间运行测试,它是一个发送到应用程序的特殊参数,还是以不同的方式编译以运行测试?

  8. ios – Xcode 6.1直到运行时才检测到单元测试

    我遇到了Xcode6.1.1没有检测到单元测试文件的问题.我运行了与之关联的方案,并在运行时找到了该文件,最后在单元测试导航器中找到了一个“rT”图标.这导致我到thisquestion,但没有一个答案对我有用.删除我的派生数据或重新启动Xcode没有任何帮助.接近工作的唯一事情是在Xcode运行时删除我的派生数据文件夹–当它重新编制索引时,它发现了我的三个方案中的一个中的所有测试文件.所有这些测

  9. xcode – 在仪器中运行SenTestingKit单元测试

    我正在开发一个数据库访问库,我试图使用已经写的单元测试检查内存泄漏.这些是基于SenTestingKit的逻辑测试,在Xcode4.2中设置了正常的方式.我可以使用Cmd-U运行它们,但是没有看到从仪器启动它们的方法,或者调用仪器来检查它们.我该怎么做这个工作?我需要编写新的案例并将其构建到应用程序中吗?

  10. Xcode:用于条件DEBUG / TEST代码的预处理器宏

    我在我的代码(例如AppDelegate.m)中有不应该为单元测试编译的部分,例如当您在创建新项目时选择“添加单元测试”时,目标是由Xcode设置的.在项目文件中,我已将标志CONfigURATION_TESTS添加到内置目标的MyAppTests的预处理器宏中,但未添加到MyApp目标.这是我发现的许多帖子中的建议方式.但是这不起作用,因为(我猜)MyAppTests目标将MyApp目标作为依赖

随机推荐

  1. 基于EJB技术的商务预订系统的开发

    用EJB结构开发的应用程序是可伸缩的、事务型的、多用户安全的。总的来说,EJB是一个组件事务监控的标准服务器端的组件模型。基于EJB技术的系统结构模型EJB结构是一个服务端组件结构,是一个层次性结构,其结构模型如图1所示。图2:商务预订系统的构架EntityBean是为了现实世界的对象建造的模型,这些对象通常是数据库的一些持久记录。

  2. Java利用POI实现导入导出Excel表格

    这篇文章主要为大家详细介绍了Java利用POI实现导入导出Excel表格,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  3. Mybatis分页插件PageHelper手写实现示例

    这篇文章主要为大家介绍了Mybatis分页插件PageHelper手写实现示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  4. (jsp/html)网页上嵌入播放器(常用播放器代码整理)

    网页上嵌入播放器,只要在HTML上添加以上代码就OK了,下面整理了一些常用的播放器代码,总有一款适合你,感兴趣的朋友可以参考下哈,希望对你有所帮助

  5. Java 阻塞队列BlockingQueue详解

    本文详细介绍了BlockingQueue家庭中的所有成员,包括他们各自的功能以及常见使用场景,通过实例代码介绍了Java 阻塞队列BlockingQueue的相关知识,需要的朋友可以参考下

  6. Java异常Exception详细讲解

    异常就是不正常,比如当我们身体出现了异常我们会根据身体情况选择喝开水、吃药、看病、等 异常处理方法。 java异常处理机制是我们java语言使用异常处理机制为程序提供了错误处理的能力,程序出现的错误,程序可以安全的退出,以保证程序正常的运行等

  7. Java Bean 作用域及它的几种类型介绍

    这篇文章主要介绍了Java Bean作用域及它的几种类型介绍,Spring框架作为一个管理Bean的IoC容器,那么Bean自然是Spring中的重要资源了,那Bean的作用域又是什么,接下来我们一起进入文章详细学习吧

  8. 面试突击之跨域问题的解决方案详解

    跨域问题本质是浏览器的一种保护机制,它的初衷是为了保证用户的安全,防止恶意网站窃取数据。那怎么解决这个问题呢?接下来我们一起来看

  9. Mybatis-Plus接口BaseMapper与Services使用详解

    这篇文章主要为大家介绍了Mybatis-Plus接口BaseMapper与Services使用详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  10. mybatis-plus雪花算法增强idworker的实现

    今天聊聊在mybatis-plus中引入分布式ID生成框架idworker,进一步增强实现生成分布式唯一ID,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

返回
顶部