小编Mar*_*dek的帖子

使用mockito进行弹簧服务单元测试

到目前为止,SO的答案已经完全满足我的问题.我正在学习Junit和Mockito的单元测试,我想测试我的服务类,这是我的Spring网络应用程序的一部分.我阅读了很多教程和文章,但仍然有问题为我的服务层编写适当的单元测试.我想知道我的问题的答案,但首先我粘贴一些代码:

服务类

public class AccountServiceImpl implements AccountService {

@Autowired
AccountDao accountDao, RoleDao roleDao, PasswordEncoder passwordEncoder, SaltSource saltSource;

@PersistenceContext
EntityManager entityManager;

public Boolean registerNewAccount(Account newAccount) {
    entityManager.persist(newAccount);
    newAccount.setPassword(passwordEncoder.encodePassword(newAccount.getPassword(), saltSource.getSalt(newAccount)));
    setRoleToAccount("ROLE_REGISTERED", newAccount);

    return checkIfUsernameExists(newAccount.getUsername());    
}

public void setRoleToAccount(String roleName, Account account) {
    List<Role> roles = new ArrayList<Role>();
    try {
        roles.add(roleDao.findRole(roleName));
    } catch(RoleNotFoundException rnf) {
        logger.error(rnf.getMessage());
    }
    account.setRoles(roles);
}

public Boolean checkIfUsernameExists(String username) {
    try {
        loadUserByUsername(username);
    } catch(UsernameNotFoundException unf) {
        return false;
    }
    return true;
}

public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException …
Run Code Online (Sandbox Code Playgroud)

java junit spring mockito

12
推荐指数
1
解决办法
2万
查看次数

@Size(min,max)但不是必需的

嗨在我的春季webapp我有一个密码变量,我想要至少0个字符或超过6个小于20.我知道有一个注释:

 @Size(min=6, max=20)
Run Code Online (Sandbox Code Playgroud)

但我不知道如何增加密码可以是0个字符的可能性.有人会帮我这个吗?

java spring hibernate-validator

7
推荐指数
2
解决办法
6511
查看次数

@InjectMocks 在使用构造函数注入时不注入 2 个相同类型的模拟

我有 2 个几乎相同的课程:

class Foo1 {
    private Bar bar1;
    private Bar bar2;

    public void setBar1(Bar bar1) {
        this.bar1 = bar1;
    }

    public void setBar2(Bar bar2) {
        this.bar2 = bar2;
    }
}

class Foo2 {
    private Bar bar1;
    private Bar bar2;

    public Foo2(Bar bar1, Bar bar2) {
        this.bar1 = bar1;
        this.bar2 = bar2;
    }
}
Run Code Online (Sandbox Code Playgroud)

所以这是setter vs构造函数。问题是@InjectMocks 只能与下面测试中的第一类一起正常工作:

@RunWith(MockitoJUnitRunner.class)
public class Test {
    @Mock
    private Bar bar1;

    @Mock
    private Bar bar2;

    @InjectMocks
    private Foo1 sut;
}
Run Code Online (Sandbox Code Playgroud)

要测试第二个类,我必须手动进行,因为对于两个 Bar 参数,@InjectMocks 选择了相同的模拟(这是随机选择)

@RunWith(MockitoJUnitRunner.class) …
Run Code Online (Sandbox Code Playgroud)

java mockito

5
推荐指数
0
解决办法
636
查看次数

Javascript正则表达式字符排除

我有一个这样的js正则表达式:

/^[a-zA-Z?ó????????Ó???????]+$/
Run Code Online (Sandbox Code Playgroud)

现在我想从像QVXqvx这样的a-zA-Z字母中排除.如何改变这个正则表达式的语法?

我试过但没有运气.请帮我.

提前致谢

javascript regex

4
推荐指数
2
解决办法
1715
查看次数

JPA Criteria Api选择列为空的对象

我在PostgreSQL DB中有一个表"word":

CREATE TABLE word
(
   word_id bigserial NOT NULL,
   word character varying(15) NOT NULL,
   counter integer NOT NULL,
   base_letters character varying(15),
   CONSTRAINT word_pk PRIMARY KEY (word_id )
)
Run Code Online (Sandbox Code Playgroud)

我有一个DAO方法,它必须在表中找到列'base_letters'的所有单词.我一般都使用Spring.我的方法:

    public List<Word> getAllWordsWithoutBaseLetters() {
        CriteriaQuery<Word> c = cb.createQuery(Word.class);
        Root<Word> words = c.from(Word.class); 
        c.select(words).where(cb.isNull(words.get("base_letters")));
        TypedQuery<Word> q = entityManager.createQuery(c);
        List<Word> allWordsWithoutBaseLetters = q.getResultList();
        return allWordsWithoutBaseLetters;
    }
Run Code Online (Sandbox Code Playgroud)

不幸的是我收到一个令我困惑的错误:

ERROR [org.springframework.scheduling.support.MethodInvokingRunnable] - Invocation of method 'setBaseLettersToAllWordsWithoutThem' on target class [class $Proxy48] failed
java.lang.IllegalArgumentException: Unable to resolve attribute [base_letters] against path
    at org.hibernate.ejb.criteria.path.AbstractPathImpl.unknownAttribute(AbstractPathImpl.java:118)
    at org.hibernate.ejb.criteria.path.AbstractPathImpl.locateAttribute(AbstractPathImpl.java:223) …
Run Code Online (Sandbox Code Playgroud)

java jpa criteria-api

4
推荐指数
1
解决办法
1万
查看次数

在Lucene文档中添加字段

你好我有一个32mb的文件.它是一个简单的字典文件,编码1250,其中有280万行.每行只有一个唯一的单词:

cat
dog
god
...
Run Code Online (Sandbox Code Playgroud)

我想用Lucene搜索特定单词字典中的每个字谜.例如:

我想搜索单词dog的每个字谜,lucene应该搜索我的字典并返回.在我的webapp中,我有一个Word实体:

public class Word {
    private Long id;
    private String word;
    private String baseLetters;
    private String definition;
}
Run Code Online (Sandbox Code Playgroud)

和baseLetters是一个变量,它按字母顺序排序,用于搜索这样的字谜[上帝和狗的单词将具有相同的baseLetters:dgo].我成功地在我的数据库中使用这个baseLetters变量在不同的服务中搜索这样的字谜但我有问题来创建我的字典文件的索引.我知道我必须添加到字段:

word和baseLetters但我不知道该怎么做:(有人能告诉我一些方向来实现这个目标吗?

现在我只有这样的东西:

public class DictionaryIndexer {

private static final Logger logger = LoggerFactory.getLogger(DictionaryIndexer.class);

@Value("${dictionary.path}")
private String dictionaryPath;

@Value("${lucene.search.indexDir}")
private String indexPath;

public void createIndex() throws CorruptIndexException, LockObtainFailedException {
    try {
        IndexWriter indexWriter = getLuceneIndexer();
        createDocument();           
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }       
 }

private IndexWriter getLuceneIndexer() throws CorruptIndexException, …
Run Code Online (Sandbox Code Playgroud)

java lucene spring

4
推荐指数
1
解决办法
5785
查看次数

奇怪的延迟加载异常

我有一个基于Spring的webapp,我的问题是在我的代码发生变化之后,我开始得到延迟加载异常.下面我详细描述一下情况:

在一开始的时候

我有一个帐户和Word实体.一个帐户可以有多个单词,一个Word可以分配给多个帐户.

Account.class

@ManyToMany(targetEntity = Word.class, fetch = FetchType.LAZY)
@JoinTable(name = "account_word", joinColumns = {@JoinColumn(name="account_id")}, inverseJoinColumns = {@JoinColumn(name="word_id")})
@OrderBy("word")
private List<Word> words;
Run Code Online (Sandbox Code Playgroud)

Word.class

@ManyToMany(targetEntity = Account.class, fetch = FetchType.LAZY, mappedBy = "words")
@JsonIgnore
private List<Account> accounts;
Run Code Online (Sandbox Code Playgroud)

除了每个帐户只能有一个"WordForToday",它由在Account.class中映射的Word实体表示,如下所示:

@OneToOne
@JoinColumn(name="word_for_today")
private Word wordForToday;
Run Code Online (Sandbox Code Playgroud)

一切都运转正常.特别是我有一个@Scheduled方法,每天调用一次,以更改每个帐户的"WordForToday":

WordServiceImpl.class

@Transactional
@Service
public class WordServiceImpl implements WordService {

@Autowired
AccountDao accountDao;

@PersistenceContext
EntityManager entityManager;

@Override
@Scheduled(cron="0 0 0 * * ?")
public void setNewWordsForToday() {
    logger.info("Starting setting new Words For Today");
    List<Account> allAccounts = accountDao.listAccounts(); …
Run Code Online (Sandbox Code Playgroud)

java spring jpa

2
推荐指数
1
解决办法
1088
查看次数

在Mockito没有调用的模拟方法

您好我有一个方法的服务:

@Service
public class CaptchaServiceImpl implements CaptchaService {

@Autowired
private MessageSource messageSource;

@Override
public boolean processCaptcha(String requestedUrl, String challenge, String userResponse) {

    ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
    reCaptcha.setPrivateKey(messageSource.getMessage("reCaptcha.private.key", new Object[]{}, new Locale("pl", "PL")));
    ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(requestedUrl, challenge, userResponse);

    return reCaptchaResponse.isValid();
}
Run Code Online (Sandbox Code Playgroud)

}

我为它写了一个测试:

@RunWith(MockitoJUnitRunner.class)
public class CaptchaServiceImplTest {

private CaptchaService captchaService;

@Mock
private MessageSource messageSource;

@Mock
private ReCaptchaImpl reCaptcha;

@Before
public void init() {
    captchaService = new CaptchaServiceImpl();
    ReflectionTestUtils.setField(captchaService, "messageSource", messageSource);
}

@Test
public void shouldPassReCaptchaValidation() {
    ReCaptchaTestResponse captchaResponse …
Run Code Online (Sandbox Code Playgroud)

java junit spring mockito

2
推荐指数
1
解决办法
6368
查看次数