简体   繁体   English

使用第三方API调用的构造函数的JUnit

[英]JUnits for constructors which uses third party API call

Below mentioned is the class that I need to test: 下面提到的是我需要测试的类:

public class MyClass {
     private String key;
     public MyClass(Connection con) {
         key = ThirdPartyApi.getkey(con);
     }
     public String getKey() {
         return key;
     }
}

Now I need to test this constructor, but am unable to mock this Third party API call. 现在,我需要测试此构造函数,但无法模拟此第三方API调用。 And the Test case would be as mentioned below : 测试用例将如下所述:

public class MyClassTest{
 @Test
 public void test1(){
     MyClass c = new MyClass(dummyconnection);
     assertNotNull(c.getKey != null);
 }
}

But this case would be giving me an error that ThirdPartyAPI Class is failing as the the connection object is mocked. 但是这种情况会给我一个错误,因为模拟了连接对象,导致ThirdPartyAPI类失败。

So I want to mock this ThirdPartyApi call. 所以我想模拟这个ThirdPartyApi调用。 Is it possible using Easymock, powermock? 是否可以使用Easymock,powermock?

Simple: EasyMock does not support mocking static calls. 简单:EasyMock不支持模拟静态调用。 So you can turn to PowerMock(ito) or JMockit in case you do not want to change your code. 所以,你可以求助于PowerMock(ITO)或JMockit你不想改变你的代码的情况。

But the better approach would be to understand that using static always leads to tight coupling between your classes, and that you want to make sure that this doesn't affect your ability to unit test your code. 但是更好的方法是理解使用静态总是会导致类之间的紧密耦合,并且您要确保这不会影响单元测试代码的能力。

In your case: 在您的情况下:

public MyClass(Connection con) {
  key = ThirdPartyApi.getkey(con);

simply replace that with: 只需将其替换为:

public MyClass(Connection con) {
  this (ThirdPartyApi.getkey(con));
}

/** unit testing only */
MyClass(Key key) {
  ...

And voila, you got a constructor that you can call from your unit test - and now you simply pass a mocked key object. 瞧,您有了一个可以从单元测试中调用的构造函数-现在您只需传递一个模拟的键对象即可。 And your tests will no longer execute that static call - because you use the key-taking constructor in all your tests. 而且您的测试将不再执行该静态调用-因为您在所有测试中都使用了键获取构造函数。

But you probably want another test case to make sure that calling the public constructor does what you expect it to do - and that could be to throw an exception because that static call fails. 但是您可能想要另一个测试用例,以确保调用公共构造函数可以实现您期望的功能-这可能会引发异常,因为该静态调用失败。

Beyond that: I fully agree with the comments - the fact that your constructor is doing so much (including static calls) has a certain design smell on it. 除此之外:我完全同意这些评论-事实上,您的构造函数正在做很多事情(包括静态调用),这具有一定的设计味道。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM